欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

js 对 只包含简单类型数据的对象 为元素 组成的数组 进行去重

程序员文章站 2023-04-04 20:10:30
/** * 对于由简单类型数据组成的对象为元素组成的数组进行去重操作 * @params {Array} 需要去重的对象数组 * @returns {Array} 去重后的对象数组 */ function distinct(sourceArray) { var resultArray = []; v ......
 1  /**
 2          * 对于由简单类型数据组成的对象为元素组成的数组进行去重操作
 3          * @params {array} 需要去重的对象数组
 4          * @returns {array} 去重后的对象数组
 5          */
 6         function distinct(sourcearray) {
 7 
 8             var resultarray = [];
 9             var i, j, currentsource, currentresult;
10 
11             for (i = 0; i < sourcearray.length; i++) {
12 
13                 currentsource = sourcearray[i];
14 
15                 if (resultarray.length === 0) {
16                     resultarray.push(currentsource);
17                     continue;
18                 }
19 
20                 for (j = 0; j < resultarray.length; j++) {
21 
22                     currentresult = resultarray[j];
23 
24                     if (!compare(currentresult, currentsource)) {
25                         resultarray.push(currentsource);
26                     }
27 
28                 }
29 
30             }
31 
32             return resultarray;
33 
34             function compare(obj1, obj2) {
35                 for (var prop in obj1) {
36 
37                     if (!obj1.hasownproperty(prop)) {
38                         continue;
39                     }
40 
41                     if (obj1[prop] !== obj2[prop]) {
42                         return false;
43                     }
44 
45                 }
46 
47                 return true;
48             }
49 
50         }

 

/**
* 对于由简单类型数据组成的对象为元素组成的数组进行去重操作
* @params {array} 需要去重的对象数组
* @returns {array} 去重后的对象数组
*/
function distinct(sourcearray) {

var resultarray = [];
var i, j, currentsource, currentresult;

for (i = 0; i < sourcearray.length; i++) {

currentsource = sourcearray[i];

if (resultarray.length === 0) {
resultarray.push(currentsource);
continue;
}

for (j = 0; j < resultarray.length; j++) {

currentresult = resultarray[j];

if (!compare(currentresult, currentsource)) {
resultarray.push(currentsource);
}

}

}

return resultarray;

function compare(obj1, obj2) {
for (var prop in obj1) {

if (!obj1.hasownproperty(prop)) {
continue;
}

if (obj1[prop] !== obj2[prop]) {
return false;
}

}

return true;
}

}