gpt4 book ai didi

javascript - 有什么方法可以区分js中的数组键类型吗? arr[1] !== 比 arr ["1"]

转载 作者:行者123 更新时间:2023-12-01 01:56:25 24 4
gpt4 key购买 nike

我试图解决数组问题中最受欢迎的项目。

我发现了一些使用映射的 O(n) 解决方案,但当您有混合数据类型时,没有什么能完全有效

[1,2,1,3,"1","a"]

“1”与 1 混合在一起。我有机会覆盖 JS 中的比较吗?或者任何可以解决这个问题的 O(n) 解决方案?

这是我使用的最流行的数组元素,考虑到您可以拥有多个相同数量的数组元素:

function getMostFrequent(array) {

if (array.length == 0)
return null;

let mapEl = {};
let maxEl = [];
let maxCount = 1;

for (let i = 0; i < array.length; i++) {
let el = array[i];

if (mapEl[el] == null) {
mapEl[el] = 1;
} else {
mapEl[el]++;
}

if (mapEl[el] > maxCount) {
maxCount = mapEl[el];
maxEl = [el];
} else if (mapEl[el] === maxCount) {
maxEl.push(el);
}

}

console.log(maxEl);
return maxEl;
}

最佳答案

some O(n) solutions using maps

map 工作得很好,因为 map “键”可以是任何类型,包括数字、字符串和对象(它们是有区别的):

const input = [1,2,1,3,"1", "1", "1", "a"];
const map = new Map();
input.forEach(key => map.set(key, (map.get(key) || 0) + 1));
console.log(
[...map.entries()].reduce((a, b) => b[1] > a[1] ? b : a)
);

也可以使用reduce,这更适合这种情况:

const input = [1,2,1,3,"1", "1", "1", "a"];
const map = input.reduce(
(map, key) => map.set(key, (map.get(key) || 0) + 1),
new Map()
);
console.log(
[...map.entries()].reduce((a, b) => b[1] > a[1] ? b : a)
);

是的,这些是O(N)

关于javascript - 有什么方法可以区分js中的数组键类型吗? arr[1] !== 比 arr ["1"],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51006028/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com