将一个指定数组去重并给出数组中出现最多的数的值

不足之处,还望指出,邮箱winnerwly@qq.com

方法-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

const arr = [1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 5]

var tmpObj = {}

arr.forEach((item) => {
if (tmpObj[item]) {
tmpObj[item].count++
} else {
tmpObj = {
...tmpObj,
[item]: {
count: 1
}
}
}

})
var tmpArr = []
for (var key in tmpObj) {
tmpArr.push({ val: key, count: tmpObj[key].count })
}

const maxVal = tmpArr.sort((a, b) => a.count < b.count).slice(0, 1)[0].val

console.log('maxVal', maxVal)
// 最多的数的值

const newArr = Array.from(new Set(arr))
// 数组去重

方法二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

const arr = [1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 5]

const newArr = Array.from(new Set(arr))
// 数组去重

const tmpArr = newArr.map((i) => {
let item = {
val: i,
count: 0
}
arr.map((j) => {
if (j === i && arr.includes(i)) {
item.count++
}
})
return item
})

const maxVal = tmpArr.sort((a, b) => a.count < b.count).slice(0, 1)[0].val

console.log('maxVal', maxVal)
// 最多的数的值

方法三(最简洁得一种方法)

1
2
3
4
5
6
7
const arr = [7, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 5]

const newArr = [...new Set(arr)]

const maxVal = newArr.map((item) => ({ val: item, count: arr.reduce((a, v) => v === item ? a + 1 : a + 0, 0) })).sort((a, b) => a.count < b.count).slice(0, 1)[0].val

console.log('maxVal', maxVal)

方法很粗糙,欢迎指教