I have a function that currently retrieves the url value for each item in an array up to a specified maximum number. Below is the code snippet:
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"]
The current function works as expected but I am considering if there is a more suitable Array method for this task.
I am aware that Array.filter
creates a new array based on a specific condition and I was wondering if it could be utilized to check another condition, specifically related to the parent array.
function getNumberOfUrls(data, num) {
return data.filter(datum => /* How can we return the url until .length === num in the data? */ )
};
Is there a way to implement this or are there better-suited Array methods for achieving this goal?
ETA: The provided example array may not fully illustrate the issue. Additional data has been added to clarify. The objective is to extract only the url values from the first three objects in the array instead of returning an array with those objects.