Ajit Goel
Ajit Goel

Reputation: 4388

Array filter method does not wok

I am trying to use the filter method to remove an item from an array based on an index but it is not working. eg: below filteredGroceries should return [{"name":"Apples","completed":false},{"name":"231312"},{"name":"765656"}]. But it returns all the elements in groceries.
I am sure I am making a newbie mistake.
What am I doing wrong?

var groceries= [{"name":"Apples","completed":false},{"name":"231312"},{"name":"454334"},{"name":"765656"}];
var indexToRemove=2;
var filteredGroceries = groceries.filter(item => item.index !== indexToRemove);   

Upvotes: 0

Views: 62

Answers (5)

Prijesh Meppayil
Prijesh Meppayil

Reputation: 540

var filteredGroceries = groceries.filter((item, i) => i !== indexToRemove);

Upvotes: 1

Lazar Nikolic
Lazar Nikolic

Reputation: 4394

var filteredGroceries = groceries.filter(item => item.index !== indexToRemove); 

This line is making new array out of existing one and it is not returning element/object that has index key in it. Considering that your array of objects contains non of the objects with key index, you get whole array back. If you would like to eliminate second element from the array, you should use groceries.splice(1, 0)

Upvotes: 0

Pablo
Pablo

Reputation: 586

Your callback returns an option item, it does not have a property index Add another params

var groceries= [{"name":"Apples","completed":false},{"name":"231312"},{"name":"454334"},{"name":"765656"}];
var indexToRemove=2;
var filteredGroceries = groceries.filter((item, index) => index !== indexToRemove); 

Upvotes: 1

Scott Marcus
Scott Marcus

Reputation: 65808

You didn't define the index argument.

var groceries= [{"name":"Apples","completed":false},{"name":"231312"},{"name":"454334"},{"name":"765656"}];
var indexToRemove=2;
var filteredGroceries = groceries.filter((item, index) => index !== indexToRemove);

console.log(filteredGroceries);

Upvotes: 1

Joe Iddon
Joe Iddon

Reputation: 20414

You are passing a function with one argument to filter whereas if you passed two, the second is the index:

var filteredGroceries = groceries.filter((item,index) => index !== indexToRemove);   

As it stands, you are accessing the 'index' attribute of each object in the array which is always undefined so all elements pass the test.

The documentation for .filter shows that to get the index, you need the second argument:

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

Upvotes: 1

Related Questions