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

Use Array.filter to return values for a set number of items

I currently have a function that returns a value for each item in my array, up to a maximum number. It looks like this

const myArray = [
    { url: "example.com/1", other: "foo" },
    { url: "example.com/sdf", other: "foo"  },
    { url: "example.com/blue", other: "foo"  },
    { url: "example.com/foo", other: "foo"  },
    { url: "example.com/123", other: "foo"  },
];

function getNumberOfUrls(data, num) {
  const newArray = [];

  data?.forEach(function (datum) {
    if (newArray.length < num) {
      newArray.push(datum.url);
    }
  });

  return newArray;
}

// Output
//["example.com/1", "example.com/sdf", "example.com/blue"] 

It simply returns the url for each object in the array until it hits the limit provided. It works fine, but I was trying to explore if there is a more suitable Array function I should be using.

I know Array.filter creates a new array based on whether the iterated item passes a particular condition, but I wondered if it could be used to check whether something else passes the condition – in this case the parent array.

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

function getNumberOfUrls(data, num) {
  return data.filter(datum => /* return url until we hit .length === num in data? */ )
};

How can I make this work or is there a better-suited Array method to achieve this?

ETA: the original example array didn’t paint the full picture. I’ve now added more data to show the issue. I don’t want to return an array with just the first three objects, I want to just return the url value from the first three objects.

>Solution :

The shortest way to do this is using Array.slice:

const myArray = [
  { url: "example.com/1" },
  { url: "example.com/sdf" },
  { url: "example.com/blue" },
  { url: "example.com/foo" },
  { url: "example.com/123" },
]

const limit = 3
const shorterArray = myArray.slice(0, limit).map(item => item.url)

console.log(shorterArray)

I removed my other code, as it was inefficient, and should not be used.

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