Building off of what Dinh Carabus said, you can use ES6's Array.prototype.reduce()
method.
const myArray = ["hello", "hi", "beep", "boop", "cromulent"];
let lengths = myArray.reduce((a, x) => ({
...a,
[x]: x.length
}), {});
Being a person who rarely uses arrow functions, I had to do a bit of searching to find out how that syntax actually works. If you, too have a hard time comprehending that, I converted it to use function()
instead of arrow functions:
let lengths = myArray.reduce(function(a, x){
return {
...a,
[x]: x.length
}
}, {});
It is always a good idea to explain, so let's review this shall we?
Array.prototype.reduce
takes 2 parameters, a function and an initial value to pass in.
Passing in the initial value allows you to reduce it into an object. In this case, we pass in an object to add into it until we are all done with iterating over our array.
As for the function, we are using two parameters - the previous value the function returned and the current value.
The spread operator adds all of the values before it, and you are adding to the object the current value you are on as the key ("x") and the length ("x.length").
I, myself was surprised something as efficient as this exists.
Of course, forEach
or a for
loop works perfectly fine, too - as another answer has demonstrated.
Sources I used:
In addition, I also decided to write a function for y'all that takes an array and returns an object with the value as its key and the length of the string as its value:
function reduceArray(array){
return array.reduce((a, x) => ({
...a,
[x]: x.length
}), {});
}
console.log(reduceArray(["hello","world!"]));