Как разделить массив по дублирующим значениям? - PullRequest
0 голосов
/ 19 января 2019

У меня есть массив объектов, Я должен разделить на повторяющиеся значения.

мой образец массива объектов,

[
    {index: 0, value: 3},
    {index: 0, value: 3},
    {index: 0, value: 3},
    {index: 1, value: 3},
    {index: 1, value: 3},
    {index: 2, value: 3}
    {index: 2, value: 3}
]

Ответ должен понравиться,

{
   0: [
       {index: 0, value: 3},
       {index: 0, value: 3},
       {index: 0, value: 3}
  ],
  1: [
       {index: 1, value: 3},
       {index: 1, value: 3},

  ],
  2: [
       {index: 2, value: 3},
       {index: 2, value: 3},

   ]
}

Ответы [ 4 ]

0 голосов
/ 20 января 2019

Вы можете использовать простой reduce, чтобы получить это:

const input=[{index:0,value:3},{index:0,value:3},{index:0,value:3},{index:1,value:3},{index:1,value:3},{index:2,value:3},{index:2,value:3}]

/* If index exists in the accumulator object, use that.
  else, create the index and point to an empty array
  push the item in context to the array
*/
const output = input.reduce((acc, v) => {
  acc[v.index] = acc[v.index] || [];
  acc[v.index].push(v);
  return acc;
}, {});

console.log(output)

Вот короткая версия:

const input=[{index:0,value:3},{index:0,value:3},{index:0,value:3},{index:1,value:3},{index:1,value:3},{index:2,value:3},{index:2,value:3}]

const output = input.reduce((a,v) => ((a[v.index] = a[v.index] || []).push(v), a), {});

console.log(output)
0 голосов
/ 19 января 2019

Здесь у вас есть одна версия, использующая lower () и Object.assign () :

const input = [
    {index: 0, value: 3},
    {index: 0, value: 3},
    {index: 0, value: 3},
    {index: 1, value: 3},
    {index: 1, value: 3},
    {index: 2, value: 3},
    {index: 2, value: 3},
    {index: 0, value: 3}
];

let obj = input.reduce((res, curr) =>
{
    if (res[[curr.index]])
        res[[curr.index]].push(curr);
    else
        res = Object.assign({[curr.index]: [curr]}, res);

    return res;
}, {});

console.log(obj);

В предыдущем примере группы всех объектов будут созданы с равным свойством index. Однако, если вы хотите отделить объекты полосами, которые имеют равные indexes, вы можете сделать это:

const input = [
    {index: 0, value: 3},
    {index: 0, value: 3},
    {index: 0, value: 3},
    {index: 1, value: 3},
    {index: 1, value: 3},
    {index: 2, value: 3},
    {index: 2, value: 3},
    {index: 0, value: 3},
    {index: 0, value: 3},
    {index: 0, value: 3},
    {index: 2, value: 3},
    {index: 2, value: 3}
];

let obj = input.reduce((res, curr) =>
{
    if (curr.index === res.last)
        res.r[res.idx - 1].push(curr);
    else
    {
        res.r = Object.assign({[res.idx]: [curr]}, res.r);
        res.last = curr.index;
        res.idx = res.idx + 1;
    }

    return res;
}, {r: {}, idx: 0, last: null});

console.log(obj.r);
0 голосов
/ 19 января 2019

Вы можете использовать простой for цикл

const input = [
    {index: 0, value: 3},
    {index: 0, value: 3},
    {index: 0, value: 3},
    {index: 1, value: 3},
    {index: 1, value: 3},
    {index: 2, value: 3},
    {index: 2, value: 3}
];

const newArray = {}
for(var i of input) {
  if(newArray[i.index]) {
    newArray[i.index].push(i)
  } else {
    newArray[i.index] = [i]
  }
}

console.log(newArray)
0 голосов
/ 19 января 2019

Выполните простую reduce операцию:

const data = [{
    index: 0,
    value: 3
  },
  {
    index: 0,
    value: 3
  },
  {
    index: 0,
    value: 3
  },
  {
    index: 1,
    value: 3
  },
  {
    index: 1,
    value: 3
  },
  {
    index: 2,
    value: 3
  }, {
    index: 2,
    value: 3
  }
];

const modified = data.reduce((val, acc) => {
  if (acc[val.index]) {
    acc[val.index].push(val);
  } else {
    acc[val.index] = [{
      index: [val.index],
      value: [val.value]
    }];
  }
  return acc;
}, {});

console.log(modified);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...