\$\begingroup\$
\$\endgroup\$
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?
Katherine MaurusKatherine Maurus
asked Feb 27, 2019 at 3:59
1 Answer 1
\$\begingroup\$
\$\endgroup\$
5
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.
answered Feb 27, 2019 at 7:25
-
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– Blindman672019年02月27日 09:58:40 +00:00Commented Feb 27, 2019 at 9:58 -
\$\begingroup\$ @Blindman67 that is good info. Do you know why
map
is so much slower? \$\endgroup\$Oh My Goodness– Oh My Goodness2019年02月27日 10:09:12 +00:00Commented Feb 27, 2019 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– Blindman672019年02月27日 10:20:06 +00:00Commented Feb 27, 2019 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– Kruga2019年02月28日 10:11:28 +00:00Commented Feb 28, 2019 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– Oh My Goodness2019年02月28日 10:54:21 +00:00Commented Feb 28, 2019 at 10:54
default