Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multi-push vs. multi-map

I’m asked to get attributes collection out of an array object,

let a = [
    {name:'aname',age:21},
    {name:'bname',age:22},
    {name:'cname',age:23},
    {name:'dname',age:24},
    {name:'ename',age:25},
    {name:'fname',age:26},
    {name:'gname',age:27}]

// wanted
let ok = {
    names:'aname;bname;cname;dname;ename;fname;gname',
    ages:'21;22;23;24;25;26;27'
}

and I got 2 ways of doing it:

alpha just using map of an array:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// alpha
let res = {
    names:'',
    ages:''
}

res.names=a.map(iter=>iter.name).join(';')
res.ages=a.map(iter=>iter.age).join(';')
//then return res

// ========================================================

and beta just iterate the array and append each attribute in the tabulation array:


// beta
let res = {
    names:[],
    ages:[]
}

a.forEach(iter=>{
    res.names.push(iter.name)
    res.ages.push(iter.age)
})
// then handle res's fields
ok.names = res.names.join(';')
ok.ages = res.ages.join(';')

so which way should I use to get the collection? Will alpha get slower or faster than beta when the objects in a get lots of fields(attrs)?

>Solution :

Both approaches are good. I’d say it depends on your personal preference what you’d want to use.

However, It seems to me that if you are aiming for performance, the following would yield better results.

let a = [
    {name:'aname',age:21},
    {name:'bname',age:22},
    {name:'cname',age:23},
    {name:'dname',age:24},
    {name:'ename',age:25},
    {name:'fname',age:26},
    {name:'gname',age:27}]
    
let ok = { names: '', ages: ''}

for (let i = 0; i < a.length; i++){
const iter = a[i]
ok.names += iter.name + ";";
ok.ages += iter.age + ";";
}

ok.names = ok.names.slice(0,-1)
ok.ages = ok.ages.slice(0,-1)

console.log(ok)

This apporach eliminates the need to create new arrays or joining them (join is a heavy operation). Just create the string you want and at the end of it all, remove the one extra semicolon.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading