数组去重

  • 通过数组方法 filer来实现
    filter方法中,有三个参数,分别是currentValue 当前元素的值,index 当前元素的索引值,arr 当前元素属于的数组对象;
const arr = [1, 2, 1, 4, 5, 6, 7, 4];
const newArr = arr.filter((currentVlaue, index, arr) => {
	return index === arr.indexOf(currentVlaue);
})
  • for循环实现
function unique(arr) {
	var res = [arr[0]];
	for (var i = 1; i < arr.length; i++) {
		var repeat = false;
		for (var j = 0; j < res.length; j++) {
			if (arr[i] == res[j]) {
				repeat = true;
				break;
			}
		}
		if (!repeat) {
			res.push(arr[i]);
		}
	}
	return res;
}
posted @ 2019-04-03 13:08  luckiest  阅读(101)  评论(0)    收藏  举报