How to remove array values โ€‹โ€‹using condition less and more than in javascript

I want to remove values โ€‹โ€‹from a number less and more than a condition, for example, my array

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 the maximum value is 130. I want to remove all other elements from the array. Is this possible in javascript.

I am new, so any help would be appreciated.

+6
source share
5 answers

Of course, 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 enable 120 and 130, etc.

+13
source

using map

$. map (a, function (o, i) {if (o <130 & o> 120) return o;})

+3
source

Just go to the filter and add it to the reusable function:

 var arr = [ 138,124,128,126,140,113,102,128,136,110,134,132,130,132,132,104,116,135,120 ] /* * @param arr Array of integers * @param min Minimum (Inclusive) * @param max Maximum (Exclusive) */ var filterInRange = function(arr, min, max) { return arr.filter(function(item) { return item >= min && item < max; }); } console.log(filterInRange(arr, 120, 131).sort()); // [120,124,126,128,128,130] 
+3
source

Use the array.prototype.filter() method to return a new array containing only those elements that pass the logical test.

  function isBigEnough(element) { return element >= 10; } var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); 

Returns a new array [12, 130, 44] .

Along with array.prototype.map() and array.prototype.reduce() array.prototype.filter() makes it easier to use the functional programming style in JavaScript.

+1
source

Just use the filter created for such things, the code below should complete the task the way you want:

 //ES6 var arr = [138,124,128,126,140,113,102,128,136,110,134,132,130,132,132,104,116,135,120]; var filteredArr = arr.filter(n => n>120 && n<130); //[124, 128, 126, 128] 
0
source

Source: https://habr.com/ru/post/974682/


All Articles