gpt4 book ai didi

javascript - 如何使用javascript从4个不同的数组中获取公共(public)值

转载 作者:行者123 更新时间:2023-11-29 21:49:59 24 4
gpt4 key购买 nike

我有下面的箭头,我想从所有四个数组中获得共同的值(value)。我已经尝试了下面的代码并且它正在工作但不是我想要的正确方式。而不是在新数组中出现 [2, 3] 它显示至少在两个或三个数组中常见的其他值。

Fiddle Demo

我的代码

var a = [11, 2, 3, 4],
b = [2, 6, 3, 5],
c = [4, 2, 20, 3],
d = [34, 2, 21, 5, 3],
result = [],
common = [];

function findCommon () {
for(var i = 0; i < arguments.length; i++){
var garr = arguments[i];
result = result.concat(arguments[i]);
};
}
findCommon(a,b,c,d);

var sorted_arr = result.sort();

for(var i = 0; i< result.length-1; i++){

if(result[i+1] == sorted_arr[i]){
common.push(result[i]);
}
};

alert(common); //[2, 2, 2, 3, 3, 4, 5]

最佳答案

您可以使用数组作为对象的值,并使用数字作为键。这样可以很容易地计算数字。请注意,这段代码也是面向 future 的,所以如果你想测试更少或更多的数组,这会让你。它还删除了各个数组的重复数据,因此每个数组中的数字只计算一次以防止错误。

function findCommon() {
var obj = {};
var out = [];
var result = [];

// convert arguments to a proper array
var args = [].slice.call(arguments);
var len = args.length;
for (var i = 0, l = len; i < l; i++) {

// grab a de-duped array and and concatenate it
// http://stackoverflow.com/a/9229821/1377002
var unique = args[i].filter(function(item, pos) {
return args[i].indexOf(item) == pos;
});
result = result.concat(unique);
}
for (var i = 0, l = result.length; i < l; i++) {
var el = result[i];

// if the object key doesn't exist, create an array
// as the value; add the number to the array
if (!obj[el]) obj[el] = [];
obj[el].push(el);
}
for (var p in obj) {

// if the array length equals the original length of
// the number of arrays added to the function
// add it to the output array, as an integer
if (obj[p].length === len) out.push(+p);
}
return out;
}

findCommon(a, b, c, d); // [2]

此外,这将找到所有多个键,因此如果将 d 中的 5 替换为 3,结果将是 [2, 3]

DEMO which uses 4 arrays, multiple hits

DEMO which uses 5 arrays

关于javascript - 如何使用javascript从4个不同的数组中获取公共(public)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29768560/

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