If have an array like this:
let array = [
{hash: "11223344", value: "abc"},
{hash: "11223344", value: "def"},
{hash: "22113344", value: "jkl"},
{hash: "22113344", value: "zyw"},
{hash: "33221144", value: "omn"},
{hash: "33221144", value: "xyz"}
];
and I wanted to loop through that array and create a new array whereby each each hash
is only listed once and each value
that was listed with a given is added to an array at the key value in the object of the single hash
, like this:
let newarray = [
{hash: "11223344", value: ["abc", "def"]},
{hash: "22113344", value: ["jkl", "zyw"]},
{hash: "33221144", value: ["omn", "xyz"]},
];
How would I get there?
Im thinking its something like
array.map((item, i, self) => {
let newArray =[];
if(item.hash === newArray.hash){
newArray.value.concat(item.value)
} else {
newArray.concat({hash: item.hash, value: [item.value]})
}
but how do I instantiate that array at first in the value
key?
Is my thinking right on the use of the Array.prototype.map()
?
EDIT: I was asked to explain how this question is different than: How to group an array of objects by key
In contrast to the link, there is no need to group the results and I dont want to use a library like LoDash. The clarity provided about creating the array in the value
key also has some worth.
I think the answers here also point out the need to use the index and provides several valid tools, some of which arent provided in the answers in the other questions. Tools such as reduce()
and Set