简体   繁体   中英

How to transform array of empty strings into empty array?

I have an array of objects:

const arr = [{name: ''}]

I want to map over this array and, if name value is "" (empty string), I want the result to be an empty array [] .

If it has values, then I want the result to be an array with the values (eg. ["Rick"]

I've tried to have a fallback value but the result is still [""]

My attempt:

const result = arr.map(a => a.name) || []

Actual result: [""]

Desired result: []

Filter the array first

 const arrWithNamesAndEmpty = [{name: ''}, {name: 'Hello'}]; const arrWithEmptyNames = [{name: ''}]; function removeEmptyNamesAndPluckName(arr) { return arr.filter(a => a.name).map(a => a.name); } console.log({ arrWithNamesAndEmpty: removeEmptyNamesAndPluckName(arrWithNamesAndEmpty), arrWithEmptyNames: removeEmptyNamesAndPluckName(arrWithEmptyNames) })

The above solution is the simplest to read but it's not the most performant. If you find yourself in a bottleneck, the reduce approach suggested by @joopmacroop is the faster version. Stay away from the flatMap solution , it's an order of magnitude slower on Chrome, Safari and Edge and it's also not as easy to understand.

See https://jsbench.me/0lkpo4lsu4/1

Table below in Ops/sec More is faster

Browser Filter + Map Reduce flatMap
Chrome 2,525,726 3,800,221 170,365
Firefox 836,111 957,237 598,365
Safari 477,305 2,089,445 367,878
Edge 2,790,834 4,819,590 217,948

I'd use reduce, to filter and map at the same time. (loops only once)

 var arr = [{name: ''}, {name:'rick'}]; var res = arr.reduce((v,p)=>{ p.name && v.push(p.name); return v; },[]); console.log(res);

You could do Array#flatMap for single loop

 var arr = [{name: ''}]; var res = arr.flatMap(a=>a.name? a.name:[]) console.log(res);

 const arr = [{name: ''}, {name: 'Rick'}] const res = arr.filter(obj => obj.name).map(obj => obj.name) console.log(res)

I have an array of objects:

const arr = [{name: ''}]

I want to map over this array and, if name value is "" (empty string), I want the result to be an empty array [] .

If it has values, then I want the result to be an array with the values (eg. ["Rick"]

I've tried to have a fallback value but the result is still [""]

My attempt:

const result = arr.map(a => a.name) || []

Actual result: [""]

Desired result: []

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM