In this article, we’ll look at how you can sort an array of strings in JavaScript.
in descending order depending on the frequency of occurrence of each word in the original list.
So here’s the challenge: there is a list of duplicate lines. It is necessary to count the number of occurrences of each word, and then sort the resulting list by the frequency of occurrence of each word in descending order.
Here’s an example:
// исходный массив
let fruits = ['banana', 'fruit', 'apple', 'apple', 'orange', 'banana', 'orange', 'banana', 'banana', 'apple'];
// должны получить,
// так как слово 'banana' встречается в исходном списке 4 раза, 'apple' - 3 раза и т.д.
['banana', 'apple', 'orange', 'fruit']
A script that solves this problem:
/**
* Сортировка элементов массива по частоте их присутствия
*
* @param {Array
*
* @returns {Array
*/
function sortByCount(array)
{
if( !Array.isArray(array) )
throw new TypeError('Неправильный тип, ожидался массив, получен ' + typeof array);
// карта для подсчета того, сколько раз встречаются строка в массиве
let valuesMap = new Map();
// проходимся по каждому элементу массива...
array.forEach(elem => {
// ... и помещаем значение в карту, увеличивая, при необходимости, значение счетчика
valuesMap.set(elem, valuesMap.has(elem) ? valuesMap.get(elem) + 1 : 1);
});
// сортируем полученный массив объектов "{'строка', число}" в порядке убывания частоты присутствия в исходном массиве
let arr = [...valuesMap.entries()].sort((a, b) => b[1] - a[1]);
// возвращаем массив, состоящий только из первых элементов
return arr.map(value => value[0]);
}
Example of use:
src=”sort_duplicated.js”> name=”viewport” content=”width=device-width, initial-scale=1.0″> http-equiv=”x-ua-compatible” content=”ie=edge”> charset=”utf-8″> lang=”en”>
Previous article Next article
Copying of materials is allowed only with the indication of the author (Mikhail Rusakov) and an indexed direct link to the site (http://myrusakov.ru)!
Add to my friends VK: http://vk.com/myrusakov.
If you want to rate me and my work, then write it in my group: http://vk.com/rusakovmy.
If you do not want to miss new materials on the site,
then you can subscribe to updates: Subscribe to updates
If you still have any questions, or you have a desire to comment on this article, then you can leave your comment at the bottom of the page.
If you liked the site, then post a link to it (on your site, on the forum, in contact):
-
Button:
It looks like this:
-
Text link:
It looks like this: How to create your website
- BB-code of the link for forums (for example, you can put it in the signature):