Advertisements
I would like to search an array of objects and create a new array of objects matching a certain criteria.
For example:
const locations = [
{
id: 1,
location: "Sydeny",
state: "nsw",
},
{
id: 2,
location: "Melbourne",
state: "victoria",
},
{
id: 3,
location: "Newcastle",
state: "nsw",
},
{
id: 4,
location: "Perth",
state: "wa",
},
];
I would like to create a new array of all the objects that match the state of nsw.
I have tried the .filter array method, but it only returns the first object.
const result = locations?.find(
({ state }) => state === 'nsw'
);
>Solution :
Just use the filter()
method like comments suggest
const locations = [
{
id: 1,
location: "Sydeny",
state: "nsw",
},
{
id: 2,
location: "Melbourne",
state: "victoria",
},
{
id: 3,
location: "Newcastle",
state: "nsw",
},
{
id: 4,
location: "Perth",
state: "wa",
},
];
const result = locations.filter(ele => ele.state=='nsw');
console.log(result);