Compare two arrays, the most concise way to remove the same value, get it in one line

Most people implement the double-layer for loop, and if the same item exists, the idea of ​​splice the same item;
like this:

function array_diff(a, b) {
	a = JSON.parse(JSON.stringify(a))
	b = JSON.parse(JSON.stringify(b))
	for (var i = 0; i < b.length; i++) {
		for (var j = 0; j < a.length; j++) {
			if (a[j] == b[i]) {
				a.splice(j, 1);
				j = j - 1;
			}
		}
	}
return a;
}

It seems cumbersome!

Teach you how to use es6 flexibly. The following line of code is done; findIndex in filter

const a = [1,2,3,4]
const b = [1, 3]
const c = a.filter(v => b.findIndex(el => el === v) === -1);
console.log(c) // [2, 4]

Guess you like

Origin blog.csdn.net/Beth__hui/article/details/105437158