Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to search an array of objects and create a new array of objects matching a certain criteria

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading