如何比较具有相同值的两个数组并将该相同值存储在新数组中
How do I compare two arrays with the same value and store that same value in a new array?
我尝试了类似的东西:
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]);
}
{
相关文章:
- csv数据中的新数组
- javascript函数,它将数组作为输入,将每个数组元素增加1,并返回增加值的新数组
- 按值名称过滤掉重复的对象,并将其放入新数组中
- 根据对多个数组唯一的元素创建一个新数组
- 使用javascript/jquery从现有数组中创建一个新数组,该数组保存项目存在的次数
- Javascript-在一个数组中搜索整个单词,并创建一个符合条件的新数组
- 使用Node中的Q promise库对值数组顺序调用/执行相同的函数;并返回带有结果的新数组/集合
- 将数组值替换为循环以创建新数组
- 带有附加元素的新数组不会可视化
- 创建新数组和清除长度之间的差异
- 如何将新数组传递给函数
- 创建新数组或增加计数器
- 将字符串数组的子字符串复制到Javascript中的新数组中
- 如何使用旧数组中的数据创建新数组
- 如何过滤/修改主干集合本身,而不是获取新数组
- 如何比较具有相同值的两个数组并将该相同值存储在新数组中
- 将现有数组的元素复制到新数组而不使用拼接
- 如何将新数组添加到另一个数组的特定对象中
- 将一个新数组放入另一个数组中
- 为什么它在创建json对象时创建数组新数组