I want to get the exact difference between two string arrays.
const array1 = [\'T\',\'E\',\'A\',\'P\',\'A\',\'P\',\'E\',\'R\'];
const array2 = [\'T\',\'A\',\
You could remove elements from allowed
based on the input
array:
const allowed = ['T','E','A','P','A','P','E','R'];
const input = ['T','A','P'];
for(const char of input) {
const pos = allowed.indexOf(char);
if(pos === -1) {
// char doesnt exist?
} else {
allowed.splice(pos, 1);
}
}
Then allowed
will be your expected result at the end.
I think filter is not correct apparoch here. Because there are some elements repeadted. Use a simple for-loop. And remove the elements when you add it to result.
const array1 = ['T','E','A','P','A','P','E','R'];
const array2 = ['T','A','P'];
const copy = [...array2];
let res = [];
for(let i = 0;i<array1.length;i++){
let index = copy.indexOf(array1[i]);
if(index === -1){
res.push(array1[i]);
}
else copy.splice(index,1);
}
console.log(res)
You could take a closure over the index for the second array and increment the index and remove this item from the result set.
var array1 = ['T', 'E', 'A', 'P', 'A', 'P', 'E', 'R'],
array2 = ['T', 'A', 'P'],
result = array1.filter((i => v => array2[i] !== v || !++i)(0));
console.log(result);
A different approach without a predefined order of array2
.
var array1 = ['T', 'E', 'A', 'P', 'A', 'P', 'E', 'R'],
array2 = ['T', 'A', 'P'],
set2 = new Set(array2)
result = array1.filter(v => !set2.delete(v));
console.log(result);