Jilco Tigchelaar
Jilco Tigchelaar

Reputation: 2149

javascript remove remove values from array smaller then value

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

Answers (6)

Kiran
Kiran

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);

DEMO

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);

DEMO

I will suggest you to go with grep based on jsperf result.

http://jsperf.com/map-vs-grep/2

Upvotes: 1

pj013
pj013

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

Jaykumar Patel
Jaykumar Patel

Reputation: 27614

In this case you can use JavaScript is good in compare of jQuery. Because JavaScript *Execution* fast compare to a jQuery.

Check this Demo jsFiddle

JavaScript

var filtered = [1,2,3,4,5,6,7,8].filter(issmall);

function issmall(element) {
    return element < 5 ;
}    

console.log(filtered);

Result

[1, 2, 3, 4] 

JavaScript filter() Method

Upvotes: 0

andrew
andrew

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);

http://jsfiddle.net/LXaqe/

Upvotes: 0

adeneo
adeneo

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;
});

FIDDLE

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])
}

FIDDLE

Upvotes: 4

panzhuli
panzhuli

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

Related Questions