是否有一种方法可以在JavaScript中返回两个数组之间的差异?
例如:
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
// need ["c", "d"]
是否有一种方法可以在JavaScript中返回两个数组之间的差异?
例如:
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
// need ["c", "d"]
当前回答
基于思考者的答案,但允许重复。
映射在映射值出现时增加它们,如果它们在另一个数组中,则减少它们。
任何剩余的部分都将包括在差额中。
function diff(curr, prev) { let a = curr.split('').sort(), b = prev.split('').sort(), c = arrDiff(a, b); console.log(JSON.stringify(a), '-', JSON.stringify(b), '=', JSON.stringify(c)); return c; } function arrDiff(larger, smaller) { var entries = {}; for (var i = 0; i < larger.length; i++) { entries[larger[i]] = (entries[larger[i]] || 0) + 1; } for (var i = 0; i < smaller.length; i++) { if (entries[smaller[i]]) { entries[smaller[i]] -= 1; } else { entries[smaller[i]] = (entries[smaller[i]] || 0) + 1; } } return Object.keys(entries).sort().reduce((diff, key) => { if (entries[key] > 0) { for (var i = 0; i < entries[key]; i++) { diff.push(key); } } return diff; }, []); } // Smaller is a subset of Larger console.log('Result:', JSON.stringify(diff('ENLIGHTEN', 'LENGTHEN'))); // [ I ] console.log('Result:', JSON.stringify(diff('STRENGTH', 'TENTHS'))); // [ G, R ] // Both have a unique value console.log('Result:', JSON.stringify(diff('BUBBLE', 'RUBBLE'))); // [ B, R ] .as-console-wrapper { top: 0; max-height: 100% !important; }
其他回答
function array_diff(a, b) {
let array = [];
for(let i = 0; i <a.length; i++) {
let k = 0;
for( let j = 0; j < b.length; j++) {
if(a[i]!==b[j]) {
k++;
}
if(k===b.length) {
array = array.concat(a[i]);
}
}
if(b.length ===0) {
array = array.concat(a[i]);
}
}
return array;
}
function diffArray(newArr, oldArr) {
var newSet = new Set(newArr)
var diff = []
oldArr.forEach((a) => {
if(!newSet.delete(a))diff.push(a)
})
return diff.concat(Array.from(newSet))
}
**这将根据'type'参数为任意2个数组返回一个唯一值数组,或一个重复值数组,或一个非重复值数组(difference)。**
let json1 = ['one', 'two']
let json2 = ['one', 'two', 'three', 'four']
function uniq_n_shit (arr1, arr2, type) {
let concat = arr1.concat(arr2)
let set = [...new Set(concat)]
if (!type || type === 'uniq' || type === 'unique') {
return set
} else if (type === 'duplicate') {
concat = arr1.concat(arr2)
return concat.filter(function (obj, index, self) {
return index !== self.indexOf(obj)
})
} else if (type === 'not_duplicate') {
let duplicates = concat.filter(function (obj, index, self) {
return index !== self.indexOf(obj)
})
for (let r = 0; r < duplicates.length; r++) {
let i = set.indexOf(duplicates[r]);
if(i !== -1) {
set.splice(i, 1);
}
}
return set
}
}
console.log(uniq_n_shit(json1, json2, null)) // => [ 'one', 'two', 'three', 'four' ]
console.log(uniq_n_shit(json1, json2, 'uniq')) // => [ 'one', 'two', 'three', 'four' ]
console.log(uniq_n_shit(json1, json2, 'duplicate')) // => [ 'one', 'two' ]
console.log(uniq_n_shit(json1, json2, 'not_duplicate')) // => [ 'three', 'four' ]
如果数组不是简单类型,则可以采用上面的答案之一:
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.map(function(e) { return JSON.stringify(e); }).indexOf(JSON.stringify(i)) < 0;});
};
这种方法适用于复杂对象的数组。
试一试。
var first = [ 1, 2, 3, 4, 5 ];
var second = [ 4, 5, 6 ];
var difference = first.filter(x => second.indexOf(x) === -1);
console.log(difference);
Output: [ 1, 2, 3]
Var first = [1,2,3,4,5]; Var second = [4,5,6]; Var差=第一。filter(x => second.indexOf(x) === -1); console.log(差异);