js数组简单去重,js数组根据对象中的元素去重

版权声明:本文为 zzwwjjdj1(意外金喜) 原创文章,非商用自由转载-保持署名-注明出处,谢谢。 https://blog.csdn.net/zzwwjjdj1/article/details/78605419

js数组简单去重

var arr1 = [1, 2, 3, 4, 5, 6, 3, 4, 3];
function arrayUnique1(arr) {
	var result = [], hash = {};
	for (var i = 0, elem; (elem = arr[i]) != null; i++) {
		if (!hash[elem]) {
			result.push(elem);
			hash[elem] = true;
		}
	}
	return result;
}
console.log(arrayUnique1(arr1));
结果:



js数组根据对象中的元素去重

var arr2 = [
	{ name: "name1", num: "1" },
	{ name: "name2", num: "11" },
	{ name: "name3", num: "12" },
	{ name: "name4", num: "13" },
	{ name: "name2", num: "1" },
	{ name: "name6", num: "12" }
]

function arrayUnique2(arr, name) {
	var hash = {};
	return arr.reduce(function (item, next) {
		hash[next[name]] ? '' : hash[next[name]] = true && item.push(next);
		return item;
	}, []);
}

console.log(arrayUnique2(arr2, "name"));
console.log(arrayUnique2(arr2, "num"));
结果:

展开阅读全文

没有更多推荐了,返回首页