Method array element deduplication

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_43606158/article/details/90205729

Today to bring friends to the weight of the array element method:

First, we define a set of data:

let array = [3, 1, 7, 1, 3, 2, 5, 4, 3, 2, 5, 7, 8, 9, 8];
let newArray = [];

Next, we are going to go heavy on him in different ways. NewArray put inside.

A: ES3 general circulation
function has(array,val){
	for(var i=0,len=array.length;i<len;i++){
		if(array[i]===val)
			return true;
	}
	return false;
}
for (let i = 0, len = array.length; i < len; i++) {
	if(!has(newArray, array[i])) {
		newArray.push(array[i]);
	}
}

Compressed to a function in:

function uniqueArray(arr) {
	let temp = [];
	for (let i = 0; i < arr.length; i++) {
		if (temp.indexOf(arr[i]) == -1) {
			temp.push(arr[i]);
		}
	}
	return temp;
}
II: Method in ES5: forEach, indexOf
array.forEach(function(curr) {
	if (newArray.indexOf(curr) === -1) {
		newArray.push(curr);
	}
})
Three: ES5 in the reduce method:
newArray = array.reduce((init, curr) => {
	if (init.indexOf(curr) === -1) {
		init.push(curr);
	}
	return init;
}, [])
Four: the ES5 in Array.from () and ES6Set () method combines:
newArray = Array.from(new Set(array));
Five: not recommended method:
let set = new Set();
array.forEach(function(curr){
	set.add(curr);
});
newArray = Array.from(set);

newArray = Array.from(new Set(array));

Whether we find that there has been no repeat of newArray the value of using the above method which will, we have completed the de-emphasis.


An array of objects to weight:

Consider this: https://blog.csdn.net/weixin_43606158/article/details/99648341

Guess you like

Origin blog.csdn.net/weixin_43606158/article/details/90205729