如何比较具有相同值的两个数组并将该相同值存储在新数组中

How do I compare two arrays with the same value and store that same value in a new array?

本文关键字:数组 新数组 存储 比较 何比较 两个      更新时间:2023-09-26

我尝试了类似的东西:

var diff = $(array1).not(array2).get();
console.log(diff); // store the difference

并将.not()替换为.is()但这不起作用..生成了错误。它只存储了差异,但我只想将相同的值存储在新数组中。如何在 jQuery 中执行此操作,无论它在两个数组中的长度大小是否相同?

var array1 = ['a','b','c','d','e','f','g'];
var array2 = ['c', 'b'];
var sameValArr = [];
// TODO:
// 1. compare the two arrays if there's any matching values in both
// 2. if yes, store the matching value in a new array; if no, do nothing
// 3. check the new array if it isn't empty 
// 4. if empty, hide the video; if not empty do nothing (show video)
    for(var i = 0; i < array1.length; i++)
    {
        for(var j = 0; j < array2.length; j++)
        {
            if(array1.indexOf([i]) === array2.indexOf([j]))
            {
               sameValArr.push(array1[i]);
                console.log("sameValArr: ", sameValArr);
            }      
        }
    }

使用indexOf()方法为此问题提供的答案不起作用。

for(var i=0; i< array1.length; i++)
{
    for(var j=0; j< array2.length; j++)
    {
        if(array1[i] === array2[j])
            sameValArr.push(array1[i]);
    }
{