You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对比两个数组的相似元素并显示元素及其对应索引?

解决方案

你已经完成了筛选共同元素的第一步,接下来只需要针对每个共同元素,获取它们在两个数组中的索引并按要求格式输出即可。注意示例中的索引是从1开始计数的,所以要把数组原生的0基索引加1转换。

基础实现代码

var array1 = ["One", "Two", "Three"];
var array2 = ["Four", "One", "Five"];

// 筛选两个数组的共同元素
const commonElements = array1.filter(value => array2.includes(value));

// 遍历每个共同元素,输出对应信息
commonElements.forEach(element => {
    // 获取array1中的1基索引
    const index1 = array1.indexOf(element) + 1;
    console.log("array1");
    console.log(`${element} - ${index1}`);
    
    // 获取array2中的1基索引
    const index2 = array2.indexOf(element) + 1;
    console.log("array2");
    console.log(`${element} - ${index2}`);
});

代码说明

  • array.indexOf(element):返回元素在数组中第一个匹配项的0基索引,加1后转为示例中的1基计数方式。
  • 遍历每个共同元素,分别输出数组名称、元素值和对应索引,完全匹配你要的输出格式。

处理重复元素的扩展版本

如果数组中存在多个相同元素(比如array1 = ["One", "Two", "One"]),上面的方法只会返回第一个匹配的索引。下面的代码可以收集所有匹配的索引:

var array1 = ["One", "Two", "One"];
var array2 = ["Four", "One", "Five", "One"];

// 封装函数:获取元素在数组中的所有1基索引
const getAllIndexes = (arr, val) => {
    return arr.reduce((acc, curr, idx) => {
        if (curr === val) acc.push(idx + 1);
        return acc;
    }, []);
};

// 筛选去重后的共同元素,避免重复输出
const uniqueCommonElements = [...new Set(array1.filter(value => array2.includes(value)))];

// 遍历输出所有匹配项
uniqueCommonElements.forEach(element => {
    console.log("array1");
    getAllIndexes(array1, element).forEach(idx => {
        console.log(`${element} - ${idx}`);
    });
    
    console.log("array2");
    getAllIndexes(array2, element).forEach(idx => {
        console.log(`${element} - ${idx}`);
    });
});

基础版本输出结果

运行基础代码后,控制台会输出:

array1
One - 1
array2
One - 2

内容的提问来源于stack exchange,提问作者Abby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 17:57:24