Sort a Javascript Array by frequency and then filter repeats

前端 未结 8 1814
南笙
南笙 2020-12-13 07:06

What is an elegant way to take a javascript array, order by the frequency of the values, and then filter for uniques?

So,

[\"apples\", \"oranges\", \"o

8条回答
  •  余生分开走
    2020-12-13 07:44

    Create a counter of the array's elements using reduce:

    arr.reduce(
      (counter, key) => {counter[key] = 1 + counter[key] || 1; return counter}, 
      {}
    );
    

    Sort the counter object using sort on Object.entries and finally show only keys.

    const arr = ["apples", "oranges", "oranges", "oranges",
      "bananas", "bananas", "oranges"
    ];
    
    // create a counter object on array
    let counter = arr.reduce(
      (counter, key) => {
        counter[key] = 1 + counter[key] || 1;
        return counter
      }, {});
    console.log(counter);
    // {"apples": 1, "oranges": 4, "bananas": 2}
    
    // sort counter by values (compare position 1 entries)
    // the result is an array
    let sorted_counter = Object.entries(counter).sort((a, b) => b[1] - a[1]);
    console.log(sorted_counter);
    // [["oranges", 4], ["bananas", 2], ["apples", 1]]
    
    // show only keys of the sorted array
    console.log(sorted_counter.map(x => x[0]));
    // ["oranges", "bananas", "apples"]

提交回复
热议问题