0

Say I have this array:

Dogs = [
    {Name: 'Sparky', OwnerID: 1},
    {Name: 'Pooch', OwnerID: 2},
    {Name: 'Sneak', OwnerID: 1}
]

What is the fastest way for me to do this:

dogNames = Dogs.map(element => element.Name);

I was just wondering if there is something like this:

dogNames = Dogs[...Name];
10
  • What's wrong with Dogs.map(element => element.Name)? You could do Dogs.map(({Name})=> Name) but that's not much of an improvement. The syntax you're proposing is not possible Commented Jan 25, 2019 at 9:30
  • Name is unknow for spreading. Commented Jan 25, 2019 at 9:31
  • @adiga Well I feel like these is something like [...] to use? @NinaScholz that was just an example... Commented Jan 25, 2019 at 9:32
  • Are the names unique? Why don't you just create an associative array/object? Get rid of the array altogether and just create one large object. Then its just Dogs['Sparky'], where your object would change to {'Sparky':1,'Pooch':2,'Sneak':1} Commented Jan 25, 2019 at 9:32
  • Possible duplicate of Pure For vs. ES6 Map | Which one to choose? Commented Jan 25, 2019 at 9:33

2 Answers 2

1

You could take a closure over the wanted key an map the result of only a single property.

const only = k => o => o[k];

var dogs = [{ Name: 'Sparky', OwnerID: 1 }, { Name: 'Pooch', OwnerID: 2 }, { Name: 'Sneak', OwnerID: 1 }],
    dogNames = dogs.map(only('Name'));
    
console.log(dogNames);

Sign up to request clarification or add additional context in comments.

2 Comments

If you measure the time from creating the array, converting it to a map then performing the look up compared to referencing an object instead of an array I think the results will be very clear....I don't think converting an array to a map is going to offer much of an increase in performance.
in sense of performance you are right. in sense of writing code, not.
0

It depends on what you mean by saying "fastest". Do you mean execution time? Fastest to type? Easiest to understand?

When "fastest to type" and "easiest to understand" is what you mean, then I'd rather say something like array.map(x => x.prop) is probably the fastest. You might find a shorter way to type it besides removing the variable and property names, but I can't think of one.

In terms of execution time, most people believe that using loops is the fastest way:

let names = [];
for (let i = 0; i < dogs.length; i += 1) {
  names[i] = dogs[i].Name;
}

Personally, I avoid loops whenever possible and stick with map, filter, reduce – to be honest, mainly because for most projects my execution time is more expensive than the execution time of my script.

Anyway, deciding that is up to you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.