Как разделить массив, чтобы отделить последующие похожие элементы в JavaScript - PullRequest
0 голосов
/ 21 мая 2019

У меня есть такой массив

var array = [
  {
    category: 'smart phone',
    name: 'Samsung Galaxy Note 4',
    color: 'golden',
    index: '1'
  },
  {
    category: 'smart phone',
    name: 'Qmobile Noir A10',
    color: 'white',
    index: '2'
  },
  {
    category: 'smart phone',
    name: 'Samsung Galaxy note 8',
    color: 'black',
    index: '3'
  },
  {
    category: 'laptop',
    name: 'Dell inspiron n5110',
    color: 'black',
    index: '4'
  },
  {
    category: 'laptop',
    name: 'Macbook Pro',
    color: 'golden',
    index: '5'
  },
  {
    category: 'smart phone',
    name: 'Samsung Galaxy S5',
    color: 'white',
    index: '6'
  },
  {
    category: 'smart phone',
    name: 'Samsung Galaxy S3',
    color: 'white',
    index: '7'
  },
];

, и я хочу разделить его на основе параллельных похожих элементов.Чтобы добиться этого, если я применяю фильтр.

array.filter(item => item.category === 'smart phone');

он не предоставляет только одновременные элементы, но отфильтровывает все элементы в категории «смартфон».

arr1 = [
  {
    category: 'smart phone',
    name: 'Samsung Galaxy Note 4',
    color: 'golden',
    index: '1'
  },
  {
    category: 'smart phone',
    name: 'Qmobile Noir A10',
    color: 'white',
    index: '2'
  },
  {
    category: 'smart phone',
    name: 'Samsung Galaxy note 8',
    color: 'black',
    index: '3'
  },
  {
    category: 'smart phone',
    name: 'Samsung Galaxy S5',
    color: 'white',
    index: '6'
  },
  {
    category: 'smart phone',
    name: 'Samsung Galaxy S3',
    color: 'white',
    index: '7'
  },
];

Я пытаюсь добиться чего-то подобного.

// output required
// concurrent items of smartphone category
arr1 = [
  {
    category: 'smart phone',
    name: 'Samsung Galaxy Note 4',
    color: 'golden',
    index: '1'
  },
  {
    category: 'smart phone',
    name: 'Qmobile Noir A10',
    color: 'white',
    index: '2'
  },
  {
    category: 'smart phone',
    name: 'Samsung Galaxy note 8',
    color: 'black',
    index: '3'
  },
];

// concurrent items of laptop category
arr2 = [
  {
    category: 'laptop',
    name: 'Dell inspiron n5110',
    color: 'black',
    index: '4'
  },
  {
    category: 'laptop',
    name: 'Macbook Pro',
    color: 'golden',
    index: '5'
  },
];

// again concurrent items of smartphone category
arr3 = [
  {
    category: 'smart phone',
    name: 'Samsung Galaxy S5',
    color: 'white',
    index: '6'
  },
  {
    category: 'smart phone',
    name: 'Samsung Galaxy S3',
    color: 'white',
    index: '7'
  },
];

Как мне достичь этого результата в JavaScript / jQuery.

Ответы [ 4 ]

2 голосов
/ 21 мая 2019

Вы можете уменьшить массив и взять новый массив для изменения категорий.

Результатом является массив массивов, в котором каждый массив имеет одинаковую категорию в исходном порядке.

var array = [{ category: 'smart phone', name: 'Samsung Galaxy Note 4', color: 'golden', index: '1' }, { category: 'smart phone', name: 'Qmobile Noir A10', color: 'white', index: '2' }, { category: 'smart phone', name: 'Samsung Galaxy note 8', color: 'black', index: '3' }, { category: 'laptop', name: 'Dell inspiron n5110', color: 'black', index: '4' }, { category: 'laptop', name: 'Macbook Pro', color: 'golden', index: '5' }, { category: 'smart phone', name: 'Samsung Galaxy S5', color: 'white', index: '6' }, { category: 'smart phone', name: 'Samsung Galaxy S3', color: 'white', index: '7' }],
    result = array.reduce((r, o, i, { [i - 1]: last = {} }) => {
        if (last.category !== o.category) r.push([]);
        r[r.length - 1].push(o);
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
2 голосов
/ 21 мая 2019

Вы можете использовать reduce для группировки объектов. Создайте переменную для отслеживания того, что было предыдущим category. Если он совпадает с текущим category, поместите объект в последний массив аккумуляторов. Иначе, вставьте новый массив в аккумулятор.

const array=[{category:'smart phone',name:'Samsung Galaxy Note 4',color:'golden',index:'1'},{category:'smart phone',name:'Qmobile Noir A10',color:'white',index:'2'},{category:'smart phone',name:'Samsung Galaxy note 8',color:'black',index:'3'},{category:'laptop',name:'Dell inspiron n5110',color:'black',index:'4'},{category:'laptop',name:'Macbook Pro',color:'golden',index:'5'},{category:'smart phone',name:'Samsung Galaxy S5',color:'white',index:'6'},{category:'smart phone',name:'Samsung Galaxy S3',color:'white',index:'7'},];

let previous;

const output = array.reduce((acc, o) => {
  if (previous !== o.category) {
    previous = o.category
    acc.push([o])
  } else {
    acc[acc.length - 1].push(o)
  }
  
  return acc;
}, [])

console.log(output)
1 голос
/ 21 мая 2019

Вы можете сделать это так, используя reduce с slice и деструктурируя:

var array = [{category:'smart phone',name:'Samsung Galaxy Note 4',color:'golden',index:'1'},{category:'smart phone',name:'Qmobile Noir A10',color:'white',index:'2'},{category:'smart phone',name:'Samsung Galaxy note 8',color:'black',index:'3'},{category:'laptop',name:'Dell inspiron n5110',color:'black',index:'4'},{category:'laptop',name:'Macbook Pro',color:'golden',index:'5'},{category:'smart phone',name:'Samsung Galaxy S5',color:'white',index:'6'},{category:'smart phone',name:'Samsung Galaxy S3',color:'white',index:'7'}];
const [[arr1, arr2, arr3]] = array.reduce(([acc, cat], curr) => {
  curr.category == cat ? acc[acc.length - 1].push(curr) : acc.push([curr]);
  return [acc, curr.category];
}, [[]]).slice(0, -1);
console.log(arr1);
console.log(arr2);
console.log(arr3);
.as-console-wrapper { max-height: 100% !important; top: auto; }
0 голосов
/ 21 мая 2019

Просто чтобы быть уверенным: вам нужно назначить вывод .filter()

let filteredArray = array.filter(item => item.category === 'smart phone');

Только запись array.filter(your function) не изменит array.

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