Reputation: 219
I'm trying to search in an array and find specific objects based on their category.
But when I run my code, I only get one result. but in the example below, I should have two results because the cat 2
exists in two of the objects!
This is what I have:
var storedArray = [{
"title": "test title 1",
"date_added": "2018-09-26",
"url": "someurl.com",
"filename": "file 1",
"category": "cat 1"
}, {
"title": "test title 2",
"date_added": "2018-10-25",
"url": "someurl.com",
"filename": "file 2",
"category": "cat 2"
},{
"title": "test title 3",
"date_added": "2018-10-25",
"url": "someurl.com",
"filename": "file 3",
"category": "cat 2"
}];
var result = storedArray.find( audio => audio.category === 'cat 2' );
console.log(result);
Could someone please advice on this issue?
Upvotes: 3
Views: 6424
Reputation: 68933
The
find()
method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
The
filter()
method creates a new array with all elements that pass the test implemented by the provided function.
From the above, you have to use filter()
to get the expected result:
var storedArray = [{
"title": "test title 1",
"date_added": "2018-09-26",
"url": "someurl.com",
"filename": "file 1",
"category": "cat 1"
}, {
"title": "test title 2",
"date_added": "2018-10-25",
"url": "someurl.com",
"filename": "file 2",
"category": "cat 2"
},{
"title": "test title 3",
"date_added": "2018-10-25",
"url": "someurl.com",
"filename": "file 3",
"category": "cat 2"
}];
var result = storedArray.filter( audio => audio.category === 'cat 2' );
console.log(result);
Upvotes: 10
Reputation: 971
The method you are using .find()
is returning only the first record that matches the condition, this is why you are getting only 1 result.
Upvotes: 0
Reputation: 279
From the MDN documentation on find...
The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
Key word: first.
Upvotes: 0
Reputation: 2367
Array.prototype.find() returns the first element found. You are looking for Array.prototype.filter()
Upvotes: 8