Say I have array like this:
[
\"foo\",
\"bar\",
\"foo\"
\"bar\",
\"bar\",
\"bar\",
\"zoom\"
]
I want to group it so I
Explanation: First, we create object (a brand new empty object). Secondly using the spread operator we first copy everything from the existing array and make a new array out of it and use that to create a new Set (the Set object lets you store unique
values) and use that as the key, and finally we filter out our array (with a little help from the length property) to see how many times a particular key
occurs and set that to the object's value
. And remember, since we used Object.assign()
and put everything inside of it, so what gets returned is an object containing the result of everything that I tried to explain (to the best of my knowledge) above :) We also used the comma operator here which simply evaluates each of its operands (from left to right) and returns the value of the last operand.
const arr = ["foo", "bar", "foo", "bar", "bar", "bar", "zoom"];
const data = Object.assign({}, ...Array.from(new Set(arr), key => ({[key]: arr.filter(value => value === key).length})));
console.log(data);