Reputation: 81
I am trying to return an array of the names who are not enabled.
let arr = [
{ enabled: false, name: 'Cal'},
{ enabled: true, name: 'John'},
{ enabled: false, name: 'Phil'},
{ enabled: true, name: 'Pierre'}
]
I am doing so with:
arr.filter(x => x.enabled).map(y => y.name)
Is there a cleaner way of doing this?
Upvotes: 1
Views: 1199
Reputation: 73
I ran some performance tests on some alternatives I've thought of. They assume the filter removes about 50% of the elements. https://jsbench.me/xll0cli8cm/1
A simple for-of loop is by far the fastest, and in my opinion more readable than reduce is.
Upvotes: 1
Reputation: 229
U can use reduce() function too.
let arr = [
{enabled:false,name:'Cal'},
{enabled:true,name:'John'},
{enabled:false,name:'Phil'},
{enabled:true,name:'Pierre'}
];
var filteredArray = arr.reduce((a,b)=> {
if (b.enabled) {
a.push(b.name);
}
return a;
},[]);
console.log(filteredArray)
Upvotes: 0
Reputation: 1133
You can use flatMap here is the documentation
let arr = [
{ enabled: false, name: 'Cal'},
{ enabled: true, name: 'John'},
{ enabled: false, name: 'Phil'},
{ enabled: true, name: 'Pierre'}
]
//empty brackets return null
const mappedArr = arr.flatMap((item)=>{
return item.enabled ? [item.name] : []
})
console.log(mappedArr)
Upvotes: 0