James Juanjie
James Juanjie

Reputation: 219

Searching in array returns only the first result

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

Answers (5)

RedKen
RedKen

Reputation: 157

You want to use filter function.

Upvotes: 4

Mamun
Mamun

Reputation: 68933

Array.prototype.find()

The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

Array.prototype.filter()

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

Simeon Stoykov
Simeon Stoykov

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

markb
markb

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

Danmoreng
Danmoreng

Reputation: 2367

Array.prototype.find() returns the first element found. You are looking for Array.prototype.filter()

Upvotes: 8

Related Questions