Skip to content Skip to sidebar Skip to footer

Finding And Removing Matching And Corresponding Values In An Array

Here's a sample of the problem I'm having in JavaScript: first array [1, 2, 3, 4, 5, 6, 7] second array [7, 8, 9, 4, 2, 5, 7] In this case, I need to be able to find and eliminat

Solution 1:

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);

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.

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);

And the final results would be

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.


Solution 2:

You could just use a for loop and use index. something like this

const firstarray = [1, 2, 3, 4, 5, 6, 7]
const secondarray = [7, 8, 9, 4, 2, 5, 7]

for (let i = 0; i <= firstarray.length - 1; i++) {
  if (firstarray[i] === secondarray[i]) {
    console.log(`found ${firstarray[i]} at index ${i}`);
    firstarray.splice(i, 1);
    secondarray.splice(i, 1);
  }
}

console.log(firstarray, secondarray);

Solution 3:

const excludeCommon = (ar1, ar2) => {
	const both = [...ar1, ...ar2].filter((v, i, ar) => v !== ar[i +  (2 * (i < ar1.length) - 1) * ar1.length]);
	return [both.slice(0, both.length / 2), both.slice(both.length / 2)];
}
console.log(excludeCommon([1, 2, 3, 4, 5, 6, 7], [7, 8, 9, 4, 2, 5, 7]));

Post a Comment for "Finding And Removing Matching And Corresponding Values In An Array"