Array to heavy

Write down any good code or special implementations you see every day

The 2019-2-21

let b = [
  {
    name: The 'color'.value: 'black'
  },
  {
    name: 'size'.value: 'xxl'
  },
  {
    name: The 'color'.value: 'white'
  },
  {
    name: 'size'.value: 'small'
  },
  {
    name: 'size'.value: 'xxl'}]Copy the code

Q&A

  • Put the same names together, value is used.segmentation
var hash = {}
var i = 0
var res = []
b.forEach(function(item) {
  var name = item.name
  hash[name]
    ? res[hash[name] - 1].value.push(item.value)
    : (hash[name] =
        ++i &&
        res.push({
          name: name,
          value: [item.value]
        }))
})
Copy the code

grok

In the future, I will update periodically every day. If I feel good, I will give a STAR

  • GitHub
  • blog