Skip to content

Instantly share code, notes, and snippets.

@andrit
Last active September 24, 2018 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrit/c8e71448b4720c81eb27f3a1baf20d5e to your computer and use it in GitHub Desktop.
Save andrit/c8e71448b4720c81eb27f3a1baf20d5e to your computer and use it in GitHub Desktop.
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 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"
  }
];

let reducedArray = array.reduce(function(acc, curr) {
  let getHashIndex = acc.findIndex(function(item) {
    return item.hash === curr.hash;
  })
  if (getHashIndex === -1) {
    let obj = {};
    obj.hash = curr.hash;
    obj.value = [];
    obj.value.push(curr.value);
    acc.push(obj)
  } else {
    acc[getHashIndex].value.push(curr.value)

  }
  return acc;
}, [])

console.log(reducedArray)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment