Reputation:
How do I solve this while using include()
?
const allowedIds = [1, 3]
const allBoats = [{
id: 1,
name: 'titanic'
}, {
id: 2,
name: 'anna'
}, {
id: 3,
name: 'boaty McBoatface'
}, ]
const expectedResult = ['boaty McBoatface', 'titanic']
Upvotes: 1
Views: 119
Reputation: 1120
if you want only those with id 1 or 3:
const selections = allBoats.filter((val)=>{return val.id === 1 || val.id ===3});
const result = selections.map((val,key)=>{ val.name}).sort()
console.log(result) //gives ["boaty McBoatface", "titanic"]
Upvotes: 0
Reputation: 22350
Consider making allowedIds
a Set and then using has
, which is O(1)
, rather than includes
on an Array, which is O(N)
:
const allowedIds = new Set([1, 3]);
const allBoats = [
{
id: 1,
name: "titanic",
},
{
id: 2,
name: "anna",
},
{
id: 3,
name: "boaty McBoatface",
},
];
const allowedBoats = allBoats.filter(b => allowedIds.has(b.id))
.map(b => b.name)
.sort();
console.log(allowedBoats);
Other potentially useful documentation links:
Upvotes: 3
Reputation: 1580
const allowedIds = [1, 3]
const allBoats = [
{
id: 1,
name: 'titanic'
},
{
id: 2,
name: 'anna'
},
{
id: 3,
name: 'boaty McBoatface'
}
]
const expectedResult = allBoats.reduce((p, c) => allowedIds.includes(c.id) ? p.concat(c.name) : p, []).sort((a, b) => a.localeCompare(b));
console.log(expectedResult);
Upvotes: 0
Reputation: 486
You can try this as well
allBoats.filter(entry => allowedIds.includes(entry.id)).map(item => item.name).sort()
Upvotes: 0
Reputation: 2330
const allowedIds = [1, 3]
const allBoats = [{
id: 1,
name: 'titanic'
}, {
id: 2,
name: 'anna'
}, {
id: 3,
name: 'boaty McBoatface'
}, ]
const result = allBoats
.filter(b => allowedIds.includes(b.id))
.map(b => b.name)
.sort((a, b) => a.localeCompare(b))
console.log('result', result)
Upvotes: 2