Reputation: 2149
I have an array in javascript like this (1,2,3,4,5,6,7,8) and i want to remove al the values that are smaller than 5. So the array that remains is (1,2,3,4). How to do this with javascript or jquery...
Upvotes: 0
Views: 1145
Reputation: 20313
Use .map()
. This will remove values less than 5 and remaining array values will be removed from array.
var arr = $.map( [ 1,2,3,4,5,6,7,8 ], function( n ) {
return n < 5 ? n : null;
});
console.log(arr);
or
Use .grep()
. This will remove values less than 5 and remaining values will be removed from the array.
var arr = $.grep( [ 1,2,3,4,5,6,7,8 ], function( n ) {
return n < 5;
});
console.log(arr);
I will suggest you to go with grep based on jsperf result.
http://jsperf.com/map-vs-grep/2
Upvotes: 1
Reputation: 1419
Var arr = [1,2,3,4,5,6,7];
var newarr = [];
For(var i=0 ; i<=arr.length ; i++){
if(arr[i] < 5){
newarr.push(arr[i]);
}
}
Upvotes: 0
Reputation: 27614
In this case you can use JavaScript is good in compare of jQuery. Because JavaScript *Execution* fast compare to a jQuery.
var filtered = [1,2,3,4,5,6,7,8].filter(issmall);
function issmall(element) {
return element < 5 ;
}
console.log(filtered);
[1, 2, 3, 4]
JavaScript filter() Method
Upvotes: 0
Reputation: 9583
var orig= [1,2,3,4,5,6,7,8];
just in case they're out of order:
var copy=orig.sort();
then:
var result = copy.splice(0,copy.lastIndexOf(4)+1);
Upvotes: 0
Reputation: 318242
You can filter the array with array.filter()
var array = [1,2,3,4,5,6,7,8];
var new_array = array.filter(function(item) {
return item < 5;
});
or if you have to support IE8 and below, you can do it the old fashion way
var array = [1,2,3,4,5,6,7,8],
new_array = [];
for (var i=0; i<array.length; i++) {
if (array[i] < 5) new_array.push(array[i])
}
Upvotes: 4
Reputation: 2940
I think you want to remove items larger than 5, but jquery grep should do it:
https://api.jquery.com/jQuery.grep/
Upvotes: 1