jquery 数组去重
在jQuery中,可以使用$.unique()方法来对数组进行去重操作。以下是示例代码:
var arr = [1, 2, 3, 4, 4, 5, 6, 6];
var uniqueArr = $.unique(arr);
console.log(uniqueArr); // [1, 2, 3, 4, 5, 6]
注意,$.unique()方法会修改原始数组并返回去重后的数组。如果需要保留原始数组,可以先复制一份再进行去重操作。
另外,如果要对包含对象的数组进行去重,需要自定义比较函数。以下是一个示例:
var arr = [
{id: 1, name: 'John'},
{id: 2, name: 'Jane'},
{id: 3, name: 'John'},
{id: 4, name: 'Jane'}
];
// 自定义比较函数
function compareFunc(a, b) {
return a.id === b.id && a.name === b.name;
}
var uniqueArr = arr.filter(function(item, index, self) {
return index === self.findIndex(function(t) {
return compareFunc(t, item);
});
});
console.log(uniqueArr);
// [
// {id: 1, name: 'John'},
// {id: 2, name: 'Jane'}
// ]
在上述代码中,我们使用Array.filter()方法结合自定义的比较函数来实现数组的去重
原文地址: https://www.cveoy.top/t/topic/hUTD 著作权归作者所有。请勿转载和采集!