Reputation: 8029
Lets say I have a list:
var list = []
Now I want to insert some value into the list in a way that its index should be according to its value
list.push(6)
list.push(2)
This will give me a result of [6, 2]
But what I want is its index should be managed according to its value.
Here 2
is smaller than 6
so 2
should come first and give result like
[2, 6]
. And if again I do list.push(1)
it should give result like [1,2,6]
and so on.
How can I achieve this in javascript ?
Upvotes: 2
Views: 137
Reputation: 2126
These other answers are missing the point, they assume that the list is already populated, and then you push in. What you need to do is compare the number you are going to push into the array, with the array itself, splicing the value in like so:
arr = [1,5,7];
var number = 0;
function findValue(value) {
return function(element, index, array) {
return (element <= value);
}
}
var filtered = arr.filter(findValue(number))
index = arr.indexOf(filtered[filtered.length-1]) +1;
arr.splice(index, 0, number);
alert(arr);
Here's a working fiddle: https://jsfiddle.net/GerardSimpson/h3t6vcka/
Upvotes: 0
Reputation: 7742
We can override push
function of list object.
var list = [];
var copyPush = list.push.bind(list);
list.push = function(){
var toret = copyPush.apply(this,arguments);
this.sort(function(a,b){ return a-b});
return toret;
}
list.push(1);
list.push(3);
list.push(2);
list.push(5);
console.log(list); //[1, 2, 3, 5]
Upvotes: 0
Reputation: 3943
You can use the sort() function.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
The result of fruits will be:
Apple,Banana,Mango,Orange
Edit: Sorry, for numbers this solution does not work. You can use this:
Sort numbers in an array in ascending order:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
The result of points will be:
1,5,10,25,40,100
Upvotes: 1
Reputation: 39342
You can use Array#sort
.
var list = [];
list.push(6);
list.push(2);
list.push(1);
list.sort(function(a, b) {
return a - b;
});
console.log(list);
Upvotes: 2
Reputation: 10083
You simply need to use Array sort function. As it treats array items as string and does not sort integers correctly by default, you need to use custom compare function for this:
var arr = [1, 22, 6, 2 ];
arr.sort(function(a, b){
return a - b;
});
console.log( arr );
Upvotes: 1