且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

查找和删除数组中的匹配值和对应值

更新时间:2022-02-07 21:20:42

如注释中所述,您可以使用

As mentioned in the comments, you may use the splice method to remove one or more elements of an array in JavaScript. First of all I would store the indexes of the elements I should remove looping the array as so:

const array1 = [1, 2, 3, 4, 5, 6, 7];
const array2 = [7, 8, 9, 4, 2, 5, 7];

//Indexes of same elements
var sameIndexes = [];

function findSameIndexes(element, index) {
  if (array1[index] == array2[index]) {
    sameIndexes.push(index);
  }
}

array1.forEach(findSameIndexes);

调用console.log(sameIndexes)应该得到以下结果:

Calling console.log(sameIndexes) should give this result:

Array [3, 6]

问题是,如果再次循环数组并按该顺序删除元素,则索引将不再与元素相对应.

The problem is that if you loop again the array and remove the elements in that order, the indexes would not correspond to the elements anymore.

例如,如果您删除第3个元素,则数字7不再位于索引6,要解决此问题,我将使用

For example if you remove the 3rd element, the number 7 wouldn't be at index 6 anymore, to solve this issue I'd use the reverse method so you won't lose track of the indexes

// A simple function to remove the elements in both arrays
function removeElements(index) {
  array1.splice(index,1);
  array2.splice(index,1);
}

sameIndexes.reverse().forEach(removeElements);

最终结果将是

Array [1, 2, 3, 5, 6]
Array [7, 8, 9, 2, 5]

希望是您要寻找的东西,当然,有更好的方式记下来,但这也许可以帮助您找到解决方案.

Which hopefully is what you were looking for, of course there are better ways to write it down, but maybe this will help you find a solution.