gpt4 book ai didi

javascript - 你有比下面的代码更聪明的算法吗

转载 作者:行者123 更新时间:2023-12-03 10:19:42 24 4
gpt4 key购买 nike

我想按数组的键进行计数。并比较它们的数量

var count = function(arr) {
    var result = {};
    for (var i = 0 ; i < arr.length ; i++) {
        var key = arr[i];
        result[key] = ++result[key] || 1;
    }
    return result
};
var diff = function(first, second) {
    var first_copy = {};
    for (var key in first) {
        first_copy[key] = first[key];
        if (second[key]) {
            first_copy[key] -= second[key]
        }
    }
    return first_copy;
};
var first = [1, 1, 1, 2, 2, 3],
    second = [1, 1, 2, 2, 2];
first = count(first);
second = count(second);
console.log(diff(first, second));
console.log(diff(second, first));

预期输出

Object {1: 1, 2: -1, 3: 1} // first - second
Object {1: -1, 2: 1} // second - first

最佳答案

如果您的目标是提高可读性,我建议使用 underscorejs ( http://underscorejs.org/ )。

以下是使用 underscorejs 的方法:

function diff(o1, o2){
return _.chain(_.keys(o1))
.map(function(e){
return [e, (o1[e] - (o2[e] || 0))];
})
.object()
.value();
}

first = [1, 1, 1, 2, 2, 3]
second = [1, 1, 2, 2, 2]

firstCount = _.countBy(first, _.id)
secondCount = _.countBy(second, _.id)

console.log(diff(firstCount, secondCount))
console.log(diff(secondCount, firstCount))

关于javascript - 你有比下面的代码更聪明的算法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29700712/

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