-1

I have an Array like this:

    const myArr = [
        { price: 100, name: 'Foo' },
        { price: 25, name: 'Foo' },
        { price: 47, name: 'Bar' },
        { price: 76, name: 'Cat' },
        { price: 85, name: 'Bar' },
        { price: 68, name: 'Bar' },
        { price: 35, name: 'Foo' },
        { price: 86, name: 'Cat' },
     ];

I want to make output like this. New array will based on main array's object name property. All the same name property should be in an individual array.

    const myNewArr = [
        [
          { price: 100, name: 'Foo' },
          { price: 25, name: 'Foo' },
          { price: 35, name: 'Foo' },
        ],
        [
          { price: 47, name: 'Bar' },
          { price: 85, name: 'Bar' },
          { price: 68, name: 'Bar' },
        ],
        [
          { price: 76, name: 'Cat' },
          { price: 86, name: 'Cat' },
        ],
      ];
4

2 回答 2

0

Here is a solution I came up with

function groupArray(array, key) {
  let result = []
  let values = []

  array.forEach(hash => {
    if(!values.includes(hash[key])) {
      values.push(hash[key])
    }
    let index = values.indexOf(hash[key])
    if(!result[index]) {
      result[index] = []
    }
    result[index].push(hash)
  })
  
  return result
}

you can then call groupArray(arr, 'name') which will return an array of arrays, sorted by the key 'name'.

于 2021-07-23T11:27:45.337 回答
0

A solution with reduce method of arrays can be presented in this way:

myNewArr = [
    [
      { price: 100, name: 'Foo' },
      { price: 25, name: 'Foo' },
      { price: 35, name: 'Foo' },
    ],
    [
      { price: 47, name: 'Bar' },
      { price: 85, name: 'Bar' },
      { price: 68, name: 'Bar' },
    ],
    [
      { price: 76, name: 'Cat' },
      { price: 86, name: 'Cat' },
    ],
  ];


let reduce1 = myArr.reduce((r, a) => {
    r[a.name] = [...(r[a.name] || []), a.symbol];
    return r;
  }, []);

console.log(Object.values(reduce1))
于 2021-07-23T15:14:35.670 回答