Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove array values using condition less than and greater than in javascript

Tags:

javascript

I want to remove values from using less than and greater than condition for example my array is

[ 138,124,128,126,140,113,102,128,136,110,134,132,130,132,132,104,116,135,120 ]

so now my minimum value is 120 and maximum value is 130. I want to remove all the remaining elements from the array. Is this possible in javascript.

I am newbie so any help would be appreciated.

like image 954
divakar Avatar asked Sep 02 '14 10:09

divakar


People also ask

How do you remove an element from an array based on a condition in JS?

To remove an object from an array by its value: Call the findIndex() method to get the index of the object in the array. Use the splice() method to remove the element at that index. The splice method changes the contents of the array by removing or replacing existing elements.

How do you remove an element from an array based on condition?

To remove elements from ArrayList based on a condition or predicate or filter, use removeIf() method. You can call removeIf() method on the ArrayList, with the predicate (filter) passed as argument. All the elements that satisfy the filter (predicate) will be removed from the ArrayList.

Which method is used to remove the elements from array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.


1 Answers

Sure, just filter the array

var arr = [
    138,124,128,126,140,113,102,128,136,110,134,132,130,132,132,104,116,135,120
]

var new_arr = arr.filter(function(x) {
    return x > 120 && x < 130;
});

FIDDLE

Use >= and <= to include 120 and 130 as well etc.

like image 186
adeneo Avatar answered Oct 04 '22 15:10

adeneo