'Efficient Way of Filtering Array and Mapping in ES6
I wanted to get array that have status of "Existing" only and don't add the status in the newArray. What is the most efficient way of doing this?
const products = [
{
"id": "111",
"name": "grapes",
"status": "Linked",
},
{
"id": "222",
"name": "banana",
"status": "Existing",
},
{
"id": "333",
"name": "mango",
"status": "Existing",
},
{
"id": "444",
"name": "salad",
"status": "Linked",
},
{
"id": "555",
"name": "juice",
"status": "Existing",
}
]
const newArray =
products?.map(({ name = '', id = '' }) => ({
name,
id,
}))
Solution 1:[1]
The most efficient in terms of lines of code is probably just a filter() followed by a map() operation:
const result = products.filter(({status}) => status === 'Existing')
.map(({id, name}) => ({id, name}));
Full snippet:
const products = [{
"id": "111",
"name": "grapes",
"status": "Linked",
}, {
"id": "222",
"name": "banana",
"status": "Existing",
}, {
"id": "333",
"name": "mango",
"status": "Existing",
}, {
"id": "444",
"name": "salad",
"status": "Linked",
}, {
"id": "555",
"name": "juice",
"status": "Existing",
}];
const result = products.filter(({status}) => status === 'Existing')
.map(({id, name}) => ({id, name}));
console.log(result);
Since that requires a double iteration, the most efficient in terms of performance will probably be an explicit for loop that pushes matching values into a result array.
If you want to do everything in a single iteration but still maintain a functional approach, you could do everything with one reduce() operation:
const products = [{
"id": "111",
"name": "grapes",
"status": "Linked",
}, {
"id": "222",
"name": "banana",
"status": "Existing",
}, {
"id": "333",
"name": "mango",
"status": "Existing",
}, {
"id": "444",
"name": "salad",
"status": "Linked",
}, {
"id": "555",
"name": "juice",
"status": "Existing",
}];
const result = products.reduce((a, {id, name, status}) => {
if (status === 'Existing') a.push({id, name});
return a;
}, []);
console.log(result);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
