数组去重的四种思想

103 阅读1分钟

第一种 排序+相邻项处理

倒序或正序数组,有相邻项只取一个,如果没有把当前项取出来。须定义一个空数组接收。

var array = [13, 23, 13, 12, 23, 7, 3, 4, 25, 4, 25, 6];
array.sort((a,b) => a-b)
array = array.join('#')+'#';
let reg = /(\d+#)\1*/g, nArray = [];
array.replace(reg, (m, g) => {
    nArray.push(g.slice(0, g.length - 1));
})
console.log(nArray);

第二种 增加新对象,数组项作为对象的属性。

如果对象中已有该属性,则删除当前项。否则给对象增加该属性。最后切记将无用的变量清除掉。

var array = [13, 23, 13, 12, 23, 7, 3, 4, 25, 4, 25, 6];
let b = {};
for (let index = 0; index < array.length; index++) {
	const element = array[index];
	/* 对象中已有该属性 删除当前项 */
	if (typeof b[element] !== 'undefined') {
		array[index] = array[array.length - 1];
		array.length--;
		index--;
		continue;
	}
	b[element] = element;
}
b = null; // 清除无用的变量
console.log(array, '++');

第三种 拿当前项去数组中查找,如果数组项中已有拿最后一项替换当前项

var array = [13, 23, 13, 12, 23, 7, 3, 4, 25, 4, 25, 6];
for (let index = 0; index < array.length; index++) {
	let element = array[index];
	let args = array.slice(index + 1);
	/* 如果当前项在数组中已有 拿最后一项来替换当前项 */
	if (args.includes(element)) {
		array[index] = array[array.length - 1];
		array.length--;
		index--;
	}
}
console.log(array, '===');

第四种,new Set + Array.from

var array = [13, 23, 13, 12, 23, 7, 3, 4, 25, 4, 25, 6];
let nArr = Array.from(new Set(array));
console.log(nArr);