Положение массива по значению объекта - PullRequest
0 голосов
/ 15 марта 2020

Я хочу создать функцию, которая сортирует массив по значению ключа c.

Я приведу пример.

[{ text: 'hi', author: 'Boy' },
{ text: 'how are you', author: 'Boy' },
{ text: 'I\'m good', author: 'Boy' },
{ text: 'hello', author: 'Girl' },
{ text: 'Bye', author: 'Boy' }]

В приведенном выше массиве 'Girl 'author больше, чем' Boy 'author, поэтому он должен вернуть следующий массив

[{ text: 'hello', author: 'Girl' },
{ text: 'hi', author: 'Boy' },
{ text: 'how are you', author: 'Boy' },
{ text: 'I\'m good', author: 'Boy' },
{ text: 'Bye', author: 'Boy' }]

Второй пример:

[{ text: 'hi', author: 'Boy' },
{ text: 'hola', author: 'Mom' },
{ text: 'how are you', author: 'Boy' },
{ text: 'I\'m good', author: 'Boy' },
{ text: 'hello', author: 'Girl' },
{ text: 'eat this', author: 'Mom' },
{ text: 'Bye', author: 'Boy' }]

Второй результат:

[{ text: 'hello', author: 'Girl' },
{ text: 'hola', author: 'Mom' },
{ text: 'eat this', author: 'Mom' },
{ text: 'hi', author: 'Boy' },
{ text: 'how are you', author: 'Boy' },
{ text: 'I\'m good', author: 'Boy' },
{ text: 'Bye', author: 'Boy' }]

Последний пример :

const data = [
  { text: 'hi', author: 'Boy' },
  { text: 'hola', author: 'Mom' },
  { text: 'hola', author: 'Mom' },
  { text: 'hola', author: 'Mom' },
  { text: 'how are you', author: 'Boy' },
  { text: "I'm good", author: 'Boy' },
  { text: 'hello', author: 'Girl' },
  { text: 'eat this', author: 'Mom' },
  { text: 'Bye', author: 'Boy' }
]

Последний результат (мне все равно, мальчик первый или мама первая

const data = [
  { text: 'hello', author: 'Girl' },
  { text: 'hola', author: 'Mom' },
  { text: 'hola', author: 'Mom' },
  { text: 'hola', author: 'Mom' },
  { text: 'eat this', author: 'Mom' },
  { text: 'hi', author: 'Boy' },
  { text: 'how are you', author: 'Boy' },
  { text: "I'm good", author: 'Boy' },
  { text: 'Bye', author: 'Boy' }
]

Ответы [ 4 ]

1 голос
/ 15 марта 2020

Если вы измените свой набор данных и добавите к нему счетчик, следующий код должен выполнить эту работу.

var data = [{ text: 'hi', author: 'Boy' },
{ text: 'hola', author: 'Mom' },
{ text: 'how are you', author: 'Boy' },
{ text: 'I\'m good', author: 'Boy' },
{ text: 'hello', author: 'Girl' },
{ text: 'eat this', author: 'Mom' },
{ text: 'Bye', author: 'Boy' }];

// add counts against each object
data.forEach(obj => {
  obj['count'] = data.filter((obj1) => obj1.author === 
    obj.author).length;
})

// user Array.sort function to sort your data
data.sort(function(a, b){
    if(a.count < b.count) return -1;
    if(a.count > b.count) return 1;
    return 0;
});

Хотя было бы лучше, если вы отсортируете этот список из серверной части.

0 голосов
/ 15 марта 2020

Вот решение этой проблемы. Вы можете использовать любое свойство для сортировки, используя эту функцию.

console.clear();
const data = [{ text: 'hi', author: 'Boy' },
{ text: 'hola', author: 'Mom' },
{ text: 'how are you', author: 'Boy' },
{ text: 'I\'m good', author: 'Boy' },
{ text: 'hello', author: 'Girl' },
{ text: 'eat this', author: 'Mom' },
{ text: 'Bye', author: 'Boy' }];

const sortBy = (value, data) => {
  let sortedData = [];
  const countValueObj = data.reduce((acc, obj) => {
    const authorValue = obj[value];
    if(!acc[authorValue]) acc[authorValue] = 1;
    else acc[authorValue]++;
    return acc;
  }, {})
  const countValueArr = Object.keys(countValueObj).sort((a, b) => countValueObj[a] - countValueObj[b]);
  countValueArr.forEach((val) => {
    const filteredData = data.filter((obj) => obj[value] === val);
    sortedData = [...sortedData, ...filteredData];
  })
  return sortedData;
}

const output = sortBy('author', data);

console.log(output)
0 голосов
/ 15 марта 2020

Вы можете сгруппировать по author и отсортировать ключи по количеству и получить новый массив объектов.

var array = [{ text: 'hi', author: 'Boy' }, { text: 'hola', author: 'Mom' }, { text: 'how are you', author: 'Boy' }, { text: 'I\'m good', author: 'Boy' }, { text: 'hello', author: 'Girl' }, { text: 'eat this', author: 'Mom' }, { text: 'Bye', author: 'Boy' }],
    temp = array.reduce((r, o) => {
        if (!r[o.author]) r[o.author] = [];
        r[o.author].push(o);
        return r;
    }, {}),
    result = Object
        .keys(temp)
        .sort((a, b) => temp[a].length - temp[b].length)
        .flatMap(k => temp[k]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
0 голосов
/ 15 марта 2020

Вы можете использовать

array.sort((a, b) => {
  return a.author - b.author;
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...