-1

Given an array of strings, return an object containing a key for every different string in the array, and the value is that string's length.

wordLen(["a", "bb", "a", "bb"])          → { "bb": 2, "a": 1 }
wordLen(["this", "and", "that", "and"])  → { "that": 4, "and": 3, "this": 4 }
wordLen(["code", "code", "code", "bug"]) → { "code": 4, "bug": 3 }
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
hatice
  • 25
  • 3

2 Answers2

1

var arr = ["a", "bb", "a", "bb"];
var entries = arr.map(x => [x, x.length]);
console.log(Object.fromEntries(entries));
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
0

You can loop through the array and store each word length in an object with the word itself being the key

function wordLen(arr){
    let words = {};
    arr.forEach(word => words[word] = word.length);
    return words;
}

Non-ES6

function wordLen(arr){
    var words = {};
    arr.forEach(function(word){ words[word] = word.length });
    return words;
}
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
Rylee
  • 1,481
  • 1
  • 6
  • 9