pjk_ok
pjk_ok

Reputation: 967

Return Multiple items with the .filter() method - JavaScript

If I have an array with a set of numbers, and want to remove certain ones with the .filter method, I understand how to do this in when i need to remove a single item (or if i can use a mathematical expression), but can't get it to work with multiple items either purely by their value or position in the array.

In the following code I would like the new array selection to return the numbers 10, 12, 15

Also, I do need to do this with the filter() method only.

JS

let random = [4, 10, 12, 15, 30];
let selection = random.filter(function(num){

  return num === [10, 12, 30];

});

Upvotes: 1

Views: 2564

Answers (4)

pjk_ok
pjk_ok

Reputation: 967

You do need a condition that will return true or false when using filter, so the simplest way to do this with the filter method would be:

let random = [4, 10, 12, 15, 30];
let selection = random.filter(function(num){

if (num > 4 && num < 16) {return true};

});

The other way to do it would be filtering by position in the array and that would be better achieved with other array methods.

Upvotes: 0

Remigius Kalimba Jr
Remigius Kalimba Jr

Reputation: 167

If I understand your question you want a function that takes a an array, checks if the elements are in your larger array and if they are there, removes them.

Filter might not be your best choice here because it doesn't alter the original array, it only makes a new array. Try using splice.

let random = [4, 10, 12, 15, 30];
function remove(array) {
  for (var i = 0; i < array.length; i++) {
    if(random.includes(array[i])){
      random.splice(random.indexOf(array[i]), 1)
    }
  }
}

remove([10, 12, 30]);
console.log(random); // [4, 15]

I am assuming you want to remove because if you already know which elements you want why filter them out? why not just pass them into your function as a new array? filter will create a new array anyways.

But if you would like to remove elements from your first array the answer above might help.

Upvotes: -1

Mark
Mark

Reputation: 92461

You can use includes:

let random = [4, 10, 12, 15, 30, 10, 10, 12, 5];
let selection = random.filter(function(num){
  var good = [10, 12, 30]
  return good.includes(num);
});

console.log(selection)

Of if you prefer the terseness of arrow function:

let random = [4, 10, 12, 15, 30, 10, 10, 12, 5];
let selection = random.filter(num => [10, 12, 30].includes(num))
console.log(selection)

Upvotes: 4

Suhair Zain
Suhair Zain

Reputation: 403

Forgive me if I do not understand it correctly, but if what you're looking for is to filter an array by the item's index, you can use the second parameter passed to the filter method's callback, which is the index.

let random = [4, 10, 12, 15, 30];
let selection = random.filter(function(num, index){
  return index > 0 && index < 4;
});
console.log(selection);

Upvotes: 1

Related Questions