如何比较两个数组,返回匹配的键并用第二个数组中的键重写第一个数组中的键。

3

我有两个数组:

const firstArray = ["A", "B", "1", "2", "F", "89", "8", "K"];
const inputArray = ["1", "B", "F", "A", "89"];

随着

for (const index of firstArray.keys()) {
  console.log(index);
}

我从我的数组中获取键值: 0, 1, 2, 3, 4, 5, 6, 7, 8

然后使用

for (const index of inputArray .keys()) {
  console.log(index);
}

我从输入数组中获取键:0、1、2、3、4。

我使用这个来比较并检查是否所有元素都在第一个数组中:

const foundedArray = inputArray.filter(element => firstArray.includes(element));

所有内容都很好,但现在我需要将第一个数组中的键获取到我的输入数组中,使它们与第一个数组中相匹配的值相对应。
我需要将第一个数组中的键获取到我的输入数组中:
Value ["1", "B", "F", "A", "89"];
Keys    2,   1,   4,   0,   5

我在这里遇到了困难,该如何编写代码。

playground: https://jsfiddle.net/alaber/u792gdfa/

谢谢!


2
你只是想获取索引还是要根据firstArray对inputArray进行排序? - Jonas Wilms
1
如果一个元素出现多次会发生什么? - briosheje
嗨,乔纳斯,是的,我尝试根据firstArray键重新排序输入数组。@briosheje 如果一个元素出现了多次,它应该只返回具有来自firstArray的索引的元素以进行排序。 - user3091744
@Josephine,那么它应该返回一个数组,对吗? - briosheje
你说的“order”是什么意思?请说明想要的结果。 - Nina Scholz
@NinaScholz请看最后一个例子,那就是我最终需要的。briosheje是的,我需要一个数组。 - user3091744
2个回答

4
  inputArray.map(it => firstArray.indexOf(it))

使用 indexOf 可以获取数组中特定值的位置。


const sortHelper = (a, b) => (a > b ? -1 : b > a ? 1 : 0);const getKeys = inputArray.map(it => firstArray.indexOf(it)).sort(sortHelper); console.log("thats their keys in first_Array: " + getKeys); 运行正常! - user3091744

1
为了获得重新排序的数组,您可以计算inputArray的值并通过检查剩余数量和减少数量来过滤firstArray

const
    firstArray = ["A", "B", "1", "2", "F", "89", "8", "K"],
    inputArray = ["1", "B", "F", "A", "89"],
    count = inputArray.reduce((count, value) => {
        count[value] = (count[value] || 0) + 1;
        return count;
    }, {}),
    result = firstArray.filter(value => count[value] && count[value]--);

console.log(result);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接