4
\$\begingroup\$

I have an array of objects:

const dataset = [
  {name: 'Marie', year: 12, country: 'Canada'},
  {name: 'Jeff', year: 18, country: 'France'},
  {name: 'Joss', year: 10, country: 'Spain'},
  {name: 'Carrie', year: 45, country: 'Belgium'},
  {name: 'Linda', year: 32, country: 'France'},
]

I want two array: one with names and one with countries:

const names = ['Marie', 'Jeff', 'Joss', 'Carrie', 'Linda']
const countries = ['Canada', 'France', 'Spain', 'Belgium', 'France']

So, I usually do:

const names = dataset.map(e => e.name)
const countries = dataset.map(e => e.country)

Is there a simplest way possibly using a single loop?

\$\endgroup\$
3
\$\begingroup\$

I'm not sure this is any simpler but it does use only a single loop:

 const dataset={ ... }
 const names=[], countries=[]
 for (var d of dataset) { 
     names.push(d.name); 
     countries.push(d.country);
 }

Surprisingly, according to jsben.ch, this approach is about 6 times faster than running map twice.

\$\endgroup\$
  • 3
    \$\begingroup\$ You can get about another 20% performance increase if you pre-allocate the array length and use destructuring to reduce the property lookup time. const names = new Array(dataset.length), countries = new Array(dataset.length); var idx = 0; for(const {name, country} of dataset) { names[idx] = name; countries[idx++] = country } \$\endgroup\$ – Blindman67 Feb 27 at 9:58
  • \$\begingroup\$ @Blindman67 that is good info. Do you know why map is so much slower? \$\endgroup\$ – Oh My Goodness Feb 27 at 10:09
  • 1
    \$\begingroup\$ Iterating the dataset twice. The overhead of a new context each time the callback is called, though you only use the first argument, the callback is passed three, and there is the preliminary, vetting and setup when map is called. You will find that map does better (improves not better than) in comparison when the array length is longer. \$\endgroup\$ – Blindman67 Feb 27 at 10:20
  • \$\begingroup\$ That test tells me that map is almost twice as fast. With Blindman67's improvements they are about the same. \$\endgroup\$ – Kruga Feb 28 at 10:11
  • \$\begingroup\$ I was testing in Firefox. In Chrome I see what you see and map is faster there. \$\endgroup\$ – Oh My Goodness Feb 28 at 10:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.