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.
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.
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.