Sort a Javascript Array by frequency and then filter repeats

前端 未结 8 1758
南笙
南笙 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 08:08

    Let me put a minimal code to get unique values (and with frequencies) in ES6.

    var arr = ["apples", "oranges", "oranges", "oranges", "bananas", "bananas", "oranges"];
    console.log([...new Set(arr)])

    It is also applied to array of objects to aggregate some properties.

    var arr = [{"fruit":"apples"}, {"fruit":"oranges"}, {"fruit":"oranges"}, {"fruit":"oranges"}, {"fruit":"bananas"}, {"fruit":"bananas"}, {"fruit":"oranges"}];
    console.log(arr.reduce((x,y)=>{if(x[y.fruit]) {x[y.fruit]++;return x;} else {var z={};z[y.fruit]=1;return Object.assign(x,z);}},{}))

提交回复
热议问题