'Get an array of strings from an array of objects with conditions
What is the best way to get an array of strings from an array of objects, where you can specify to only take value x where value y=z?
Current solution:
array = [{
"Item": "A",
"Quantity": 2
},
{
"Item": "B",
"Quantity": 7
},
{
"Item": "C",
"Quantity": 7
},
{
"Item": "D",
"Quantity": 7
},
{
"Item": "E",
"Quantity": 7
},
{
"Item": "F",
"Quantity": 1
}
];
let filteredValues = array.map((el) => el.Quantity === 7 && el.Item);
console.log(filteredValues)
Expected outcome:
["B", "C", "D", "E"]
Actual outcome:
[false, "B", "C", "D", "E", false]
Additional info: using next.js / react
Solution 1:[1]
First, do filter and then do a map to get only the property you need.
const array = [
{ Item: "A", Quantity: 2 },
{ Item: "B", Quantity: 7 },
{ Item: "C", Quantity: 7 },
{ Item: "D", Quantity: 7 },
{ Item: "E", Quantity: 7 },
{ Item: "F", Quantity: 1 },
];
let filteredValues = array
.filter((el) => el.Quantity === 7 && el.Item)
.map(({ Item }) => Item);
console.log(filteredValues);
Or, you can use reduce as below.
const array = [
{ Item: "A", Quantity: 2 },
{ Item: "B", Quantity: 7 },
{ Item: "C", Quantity: 7 },
{ Item: "D", Quantity: 7 },
{ Item: "E", Quantity: 7 },
{ Item: "F", Quantity: 1 },
];
let filteredValues = array.reduce((results, el) => {
if (el.Quantity === 7 && el.Item) {
results.push(el.Item);
}
return results;
}, []);
console.log(filteredValues);
Solution 2:[2]
The best way is to use Array.prototype.reduce
let data = [{
"Item": "A",
"Quantity": 2
},
{
"Item": "B",
"Quantity": 7
},
{
"Item": "C",
"Quantity": 7
},
{
"Item": "D",
"Quantity": 7
},
{
"Item": "E",
"Quantity": 7
},
{
"Item": "F",
"Quantity": 1
}
];
const result = data.reduce((accumulator, current) => {
return current["Quantity"] === 7 ? accumulator.concat(current["Item"]): accumulator;
}, [])
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 | |
| Solution 2 | Yves Kipondo |
