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

 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;
}

}

猜你喜欢

转载自www.cnblogs.com/JosephBee/p/11322510.html