gpt4 book ai didi

javascript - 在javascript中搜索两个具有重复值的数组中的匹配值

转载 作者:行者123 更新时间:2023-12-03 06:54:58 24 4
gpt4 key购买 nike

我有两个数组:

a = [2,2,3,0,6]
b = [6,3,2,2,0]

我正在尝试使用 for 循环来匹配值并获取新数组 c 中 a 的索引。我们应该怎么做?请注意,有多个匹配的值,因此我认为必须跳过前一个匹配。

最佳答案

这是一个尊重最后一个索引并看得更远的提案。

How it works:

It uses Array#map for iterating array b with a callback. map gets an own this space with an really empty object Object.create(null).

The callback has on parameter bb which is one element of `b.

Next is to find the element is in array a with a Array#indexOf and a fromIndex, based on the former searches. The former index is stored in the this object, as long as the result is not -1, because this would reset the fromIndex to zero.

If there is no this[bb] or a falsy value of this[bb] take zero as fromIndex.

Later, a found index is incremented and stored in this[bb].

At least, the index is returned.

var a = [2, 2, 3, 0, 6],
b = [6, 3, 2, 2, 0],
c = b.map(function (bb) {
var index = a.indexOf(bb, this[bb] || 0);
if (index !== -1) {
this[bb] = index + 1;
}
return index;
}, Object.create(null));

console.log(c);

另一种解决方案可以首先生成一个包含 a 的所有索引的对象,并在 b 的迭代中使用它来返回索引。

该示例进行了一些扩展,以显示如果索引不超过两个 (2) 并且一个不在 a (7) 中,会发生什么情况。

The content of aObj with all indices of a:

{
"0": [3],
"2": [0, 1],
"3": [2],
"6": [4]
}

var a = [2, 2, 3, 0, 6],
b = [6, 3, 2, 2, 0, 7, 2],
aObj = Object.create(null),
c;

a.forEach(function (aa, i) {
aObj[aa] = aObj[aa] || [];
aObj[aa].push(i);
});
c = b.map(function (bb) {
return aObj[bb] && aObj[bb].length ? aObj[bb].shift() : -1;
});

console.log(c);

关于javascript - 在javascript中搜索两个具有重复值的数组中的匹配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37319802/

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