How to insert number into an array in order?


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
66 views
The essence of the question is very simple: given an array [2,4,7,10] how to insert, for example, the number five in order? That is to say that it is between 4 and 7.
by | 66 views

5 Answers

0 like 0 dislike
function insert(n, arr) { let i = 0; while (n > arr[i]) i++; arr.splice(i, 0, n); return arr; }
by
0 like 0 dislike
let insert = n => (a, r = [ ], [h, t...] = a) => a.length == 0 ? [n] : n > a[a.length - 1] ? [...a, n] : n <= h ? [...r n ...a] : insert(n)(t, [..., r, h]) let f = insert(0) let g = insert(5) let h = insert(11) let a = [ ] let b = [2, 4, 7, 10] f(a) //=> [<0>] f(b) //=> [<0>, 2, 4, 7, 10] g(b) //=> [2, 4, <In section 5, 7, 10] h(b) //=> [2, 4, 7, 10, <11>]
by
0 like 0 dislike
by
0 like 0 dislike
/* write a function sort in ascending order*/ function sortAsc( a, b ) { return a - b; } const arr = [2, 4, 7, 10]; arr.push(5); /* use the function sort in ascending order*/ arr.sort(sortAsc);
by
0 like 0 dislike
It is possible here so:
[2,4,7,10].concat(5).sort((a,b)=>a-b);
by

Related questions

0 like 0 dislike
1 answer
asked Apr 14, 2019 by polyanin
0 like 0 dislike
1 answer
asked May 20, 2019 by Franchesko
0 like 0 dislike
2 answers
0 like 0 dislike
2 answers
0 like 0 dislike
2 answers
asked Apr 14, 2019 by maiskiykot
110,608 questions
257,186 answers
0 comments
35,535 users