Reputation: 11389
All:
Say I have an array of object, each one has value attr. What I want to do is :
Loop thru the array and remove the objects whose value is less than 1,
I thought of using splice or create another array, push those whose value>=1 into it then return new array, I wonder which way is better? Or any other efficient way?
Thanks
Upvotes: 0
Views: 78
Reputation: 275
From the question if you are talking about array of object below is the solution which will keep intact the original array and its more efficient as well.
Use delete operator which will put undefined on indexes which have value<=1
<!doctype html>
<html>
<head>
<script>
var obj1 = {
value: 0
};
var obj2 = {
value: 10
};
var arr = [obj1, obj2];
arr.forEach(function(x, counter, arr) {
if (arr[counter].value <= 1)
delete arr[counter];
});
arr.forEach(function(x, counter, arr) {
document.write(arr[counter].value);
});
</script>
</head>
</html>
Upvotes: 0
Reputation: 66999
If you want to keep the original array intact:
arr.filter(function(elem) {
return elem.value >= 1;
})
My reading of your question led me to understand that each array element has a value
property. If, instead, each element is just the actual value being compared, then replace "elem.value" with "elem".
[UPDATE]
Based on a jsperf comparison, if you are OK with modifying the original array, the splice
approach presented in @NicholasHazel's answer is actually an order of magnitude faster.
I even tried a third approach using slice()
to first make a copy of the original array, and then using splice()
on the copy, but that was much slower than the other approaches.
Upvotes: 2
Reputation: 3750
For efficiency sake, splice will be your most optimum performance solution. As long as you don't need the initial array any more, I would just convert the variable entirely.
var array = [-5,-4,-3,-2,-1,0,1,2,3,4,5];
for(var i=array.length-1; i>=0; i--){
if(array[i] < 1) {
array.splice(i,1);
}
}
If you do have a need to utilize the initial array at a later time, pushing to a new array is your best bet:
var array = [-5,-4,-3,-2,-1,0,1,2,3,4,5];
var newArray = [];
for(var i=array.length-1; i>=0; i--){
if(array[i] < 1) {
newArray.push(array[i]);
}
}
Both are perfectly reasonable solutions.
Upvotes: 1
Reputation: 1263
Internally splice is doing a new array, so behind the scenes you'll create new array for every object you want to remove. This means creating one array an pushing to it only wanted objects is much more efficient than splice.
Upvotes: 1