JavaScript에서 두 어레이의 차이를 확인하는 방법
JavaScript에서 두 어레이 간의 차이를 반환하는 방법이 있습니까?
예를 들어 다음과 같습니다.
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
// need ["c", "d"]
ES7을 사용하는 더 나은 방법이 있습니다.
교차로
let intersection = arr1.filter(x => arr2.includes(x));
★★★의 [1,2,3] [2,3]
산출된다[2,3]
,,의 경우[1,2,3] [2,3,5]
같은 것을 돌려줍니다.
차이
let difference = arr1.filter(x => !arr2.includes(x));
★★★의 [1,2,3] [2,3]
산출된다[1]
,,의 경우[1,2,3] [2,3,5]
같은 것을 돌려줍니다.
대칭 차이의 경우 다음을 수행할 수 있습니다.
let difference = arr1
.filter(x => !arr2.includes(x))
.concat(arr2.filter(x => !arr1.includes(x)));
이렇게 하면 ar2에 없는 ar1의 모든 요소를 포함하는 배열을 얻을 수 있으며 그 반대도 마찬가지입니다.
@Joshaven Potter가 답변에서 지적한 바와 같이 Array.protype에 이를 추가하여 다음과 같이 사용할 수 있습니다.
Array.prototype.diff = function(arr2) { return this.filter(x => !arr2.includes(x)); }
[1, 2, 3].diff([2, 3])
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;});
};
//////////////
// Examples //
//////////////
const dif1 = [1,2,3,4,5,6].diff( [3,4,5] );
console.log(dif1); // => [1, 2, 6]
const dif2 = ["test1", "test2","test3","test4","test5","test6"].diff(["test1","test2","test3","test4"]);
console.log(dif2); // => ["test5", "test6"]
★★★ .indexOf()
★★★★★★★★★★★★★★★★★」.filter()
는 IE9이전 할 수 없습니다.
이 답변은 2009년에 작성되었기 때문에 다소 시대에 뒤떨어져 있고 문제를 이해하는 데 교육적인 내용입니다.오늘 제가 사용하는 가장 좋은 솔루션은
let difference = arr1.filter(x => !arr2.includes(x));
(여기서 다른 작성자에게 참조)
정상적인 어레이를 비교하고 있다고 생각합니다.그렇지 않으면 for 루프를 for로 변경해야 합니다. 루프를 이루다
function arr_diff (a1, a2) {
var a = [], diff = [];
for (var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}
for (var k in a) {
diff.push(k);
}
return diff;
}
console.log(arr_diff(['a', 'b'], ['a', 'b', 'c', 'd']));
console.log(arr_diff("abcd", "abcde"));
console.log(arr_diff("zxc", "zxc"));
jQuery를 사용하여 원하는 결과를 얻을 수 있는 가장 쉬운 방법입니다.
var diff = $(old_array).not(new_array).get();
diff
, 그럼 에 나왔던 요.old_array
것new_array
언더스코어(또는 그 드롭인 대체품인 Lo-Dash)의 차이 방식에서도 이 작업을 수행할 수 있습니다.
(R)eturns the values from array that are not present in the other arrays
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]
언더스코어 함수와 마찬가지로 보다 객체 지향적인 스타일로 사용할 수도 있습니다.
_([1, 2, 3, 4, 5]).difference([5, 2, 10]);
플레인 자바스크립트
"차이"에 대한 두 가지 가능한 설명이 있습니다.네가 원하는 걸 고를 수 있게 해줄게.예를 들어 다음과 같습니다.
var a1 = ['a', 'b' ];
var a2 = [ 'b', 'c'];
당신이 원한다면
['a']
, 이function difference(a1, a2) { var result = []; for (var i = 0; i < a1.length; i++) { if (a2.indexOf(a1[i]) === -1) { result.push(a1[i]); } } return result; }
당신이 원한다면
['a', 'c']
(다음 중 하나에 포함되는 모든 요소a1
★★★★★★★★★★★★★★★★★」a2
둘 다 아닌 이른바 대칭 차이)는 다음 함수를 사용합니다.function symmetricDifference(a1, a2) { var result = []; for (var i = 0; i < a1.length; i++) { if (a2.indexOf(a1[i]) === -1) { result.push(a1[i]); } } for (i = 0; i < a2.length; i++) { if (a1.indexOf(a2[i]) === -1) { result.push(a2[i]); } } return result; }
Lodash / 밑줄
lodash를 사용하는 경우 (위의 케이스 1) 또는 (케이스 2)를 사용할 수 있습니다.
Underscore.js 를 사용하고 있는 경우는, 이 함수를 케이스 1 에 사용할 수 있습니다.
ES6 세트(대규모 어레이용)
위의 코드는 모든 브라우저에서 작동합니다.그러나 약 10,000개 이상의 항목을 포함하는 대규모 어레이의 경우 O(n²) 복잡성이 있기 때문에 매우 느려집니다.많은 최신 브라우저에서는 ES6 오브젝트를 사용하여 작업 속도를 높일 수 있습니다.Lodash는 자동으로Set
가능한 한 빨리 찾아보세요.Lodash를 사용하지 않는 경우 Axel Rauschmayer의 블로그 게시물에서 영감을 받아 다음 구현을 사용하십시오.
function difference(a1, a2) {
var a2Set = new Set(a2);
return a1.filter(function(x) { return !a2Set.has(x); });
}
function symmetricDifference(a1, a2) {
return difference(a1, a2).concat(difference(a2, a1));
}
메모들
-0, +0, NaN 또는 스파스 배열에 관심이 있는 경우 모든 예에서 동작이 놀랍거나 명확하지 않을 수 있습니다(대부분의 경우 이는 문제가 되지 않습니다).
ES6의 보다 깔끔한 접근방식은 다음과 같습니다.
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
차이
a2.filter(d => !a1.includes(d)) // gives ["c", "d"]
교차로
a2.filter(d => a1.includes(d)) // gives ["a", "b"]
분리 결합(대칭 차이)
[ ...a2.filter(d => !a1.includes(d)),
...a1.filter(d => !a2.includes(d)) ]
대칭적인 차이를 얻으려면 양쪽(또는 여러 어레이의 경우 모든 방법으로) 어레이를 비교해야 합니다.
ES7 (ECMAScript 2016)
// diff between just two arrays:
function arrayDiff(a, b) {
return [
...a.filter(x => !b.includes(x)),
...b.filter(x => !a.includes(x))
];
}
// diff between multiple arrays:
function arrayDiff(...arrays) {
return [].concat(...arrays.map( (arr, i) => {
const others = arrays.slice(0);
others.splice(i, 1);
const unique = [...new Set([].concat(...others))];
return arr.filter(x => !unique.includes(x));
}));
}
ES6 (ECMAScript 2015)
// diff between just two arrays:
function arrayDiff(a, b) {
return [
...a.filter(x => b.indexOf(x) === -1),
...b.filter(x => a.indexOf(x) === -1)
];
}
// diff between multiple arrays:
function arrayDiff(...arrays) {
return [].concat(...arrays.map( (arr, i) => {
const others = arrays.slice(0);
others.splice(i, 1);
const unique = [...new Set([].concat(...others))];
return arr.filter(x => unique.indexOf(x) === -1);
}));
}
ES5(ECMAScript 5.1)
// diff between just two arrays:
function arrayDiff(a, b) {
var arrays = Array.prototype.slice.call(arguments);
var diff = [];
arrays.forEach(function(arr, i) {
var other = i === 1 ? a : b;
arr.forEach(function(x) {
if (other.indexOf(x) === -1) {
diff.push(x);
}
});
})
return diff;
}
// diff between multiple arrays:
function arrayDiff() {
var arrays = Array.prototype.slice.call(arguments);
var diff = [];
arrays.forEach(function(arr, i) {
var others = arrays.slice(0);
others.splice(i, 1);
var otherValues = Array.prototype.concat.apply([], others);
var unique = otherValues.filter(function (x, j) {
return otherValues.indexOf(x) === j;
});
diff = diff.concat(arr.filter(x => unique.indexOf(x) === -1));
});
return diff;
}
예제:
// diff between two arrays:
const a = ['a', 'd', 'e'];
const b = ['a', 'b', 'c', 'd'];
arrayDiff(a, b); // (3) ["e", "b", "c"]
// diff between multiple arrays
const a = ['b', 'c', 'd', 'e', 'g'];
const b = ['a', 'b'];
const c = ['a', 'e', 'f'];
arrayDiff(a, b, c); // (4) ["c", "d", "g", "f"]
오브젝트 배열의 차이
function arrayDiffByKey(key, ...arrays) {
return [].concat(...arrays.map( (arr, i) => {
const others = arrays.slice(0);
others.splice(i, 1);
const unique = [...new Set([].concat(...others))];
return arr.filter( x =>
!unique.some(y => x[key] === y[key])
);
}));
}
예제:
const a = [{k:1}, {k:2}, {k:3}];
const b = [{k:1}, {k:4}, {k:5}, {k:6}];
const c = [{k:3}, {k:5}, {k:7}];
arrayDiffByKey('k', a, b, c); // (4) [{k:2}, {k:4}, {k:6}, {k:7}]
이 경우 세트를 사용할 수 있습니다.이러한 조작(유니온, 교차, 차이)에 최적화되어 있습니다.
중복이 허용되지 않으면 해당 사항이 귀하의 사례에 적용되도록 하십시오.
var a = new JS.Set([1,2,3,4,5,6,7,8,9]);
var b = new JS.Set([2,4,6,8]);
a.difference(b)
// -> Set{1,3,5,7,9}
function diff(a1, a2) {
return a1.concat(a2).filter(function(val, index, arr){
return arr.indexOf(val) === arr.lastIndexOf(val);
});
}
양쪽 어레이를 Marge하면 하나의 값이 한 번만 표시되므로 indexOf()는 lastIndexOf()와 동일합니다.
세트 및 스플래트 연산자와 함께 ES6가 도착하면(Firefox에서만 작동하는 경우 호환성 표 확인), 다음 라이너 하나를 작성할 수 있습니다.
var a = ['a', 'b', 'c', 'd'];
var b = ['a', 'b'];
var b1 = new Set(b);
var difference = [...new Set(a.filter(x => !b1.has(x)))];
which which which which which which which 。[ "c", "d" ]
.
라이너 1개
const unique = (a) => [...new Set(a)];
const uniqueBy = (x,f)=>Object.values(x.reduce((a,b)=>((a[f(b)]=b),a),{}));
const intersection = (a, b) => a.filter((v) => b.includes(v));
const diff = (a, b) => a.filter((v) => !b.includes(v));
const symDiff = (a, b) => diff(a, b).concat(diff(b, a));
const union = (a, b) => diff(a, b).concat(b);
const a = unique([1, 2, 3, 4, 5, 5]);
console.log(a);
const b = [4, 5, 6, 7, 8];
console.log(intersection(a, b), diff(a, b), symDiff(a, b), union(a, b));
console.log(uniqueBy(
[
{ id: 1, name: "abc" },
{ id: 2, name: "xyz" },
{ id: 1, name: "abc" },
],
(v) => v.id
));
const intersectionBy = (a, b, f) => a.filter((v) => b.some((u) => f(v, u)));
console.log(intersectionBy(
[
{ id: 1, name: "abc" },
{ id: 2, name: "xyz" },
],
[
{ id: 1, name: "abc" },
{ id: 3, name: "pqr" },
],
(v, u) => v.id === u.id
));
const diffBy = (a, b, f) => a.filter((v) => !b.some((u) => f(v, u)));
console.log(diffBy(
[
{ id: 1, name: "abc" },
{ id: 2, name: "xyz" },
],
[
{ id: 1, name: "abc" },
{ id: 3, name: "pqr" },
],
(v, u) => v.id === u.id
));
타입 스크립트
const unique = <T>(array: T[]) => [...new Set(array)];
const intersection = <T>(array1: T[], array2: T[]) =>
array1.filter((v) => array2.includes(v));
const diff = <T>(array1: T[], array2: T[]) =>
array1.filter((v) => !array2.includes(v));
const symDiff = <T>(array1: T[], array2: T[]) =>
diff(array1, array2).concat(diff(array2, array1));
const union = <T>(array1: T[], array2: T[]) =>
diff(array1, array2).concat(array2);
const intersectionBy = <T>(
array1: T[],
array2: T[],
predicate: (array1Value: T, array2Value: T) => boolean
) => array1.filter((v) => array2.some((u) => predicate(v, u)));
const diffBy = <T>(
array1: T[],
array2: T[],
predicate: (array1Value: T, array2Value: T) => boolean
) => array1.filter((v) => !array2.some((u) => predicate(v, u)));
const uniqueBy = <T>(
array: T[],
predicate: (v: T, i: number, a: T[]) => string
) =>
Object.values(
array.reduce((acc, value, index) => {
acc[predicate(value, index, array)] = value;
return acc;
}, {} as { [key: string]: T })
);
하나의 어레이를 다른 어레이에서 빼려면 아래의 스니펫을 사용하십시오.
var a1 = ['1','2','3','4','6'];
var a2 = ['3','4','5'];
var items = new Array();
items = jQuery.grep(a1,function (item) {
return jQuery.inArray(item, a2) < 0;
});
두 번째 배열에는 존재하지 않는 첫 번째 배열 항목인 [1], [2], [6]을 반환합니다.
따라서 문제 샘플에 따르면 다음 코드가 정확한 해결책입니다.
var array1 = ["test1", "test2","test3", "test4"];
var array2 = ["test1", "test2","test3","test4", "test5", "test6"];
var _array = new Array();
_array = jQuery.grep(array2, function (item) {
return jQuery.inArray(item, array1) < 0;
});
문제를 해결하는 또 다른 방법
function diffArray(arr1, arr2) {
return arr1.concat(arr2).filter(function (val) {
if (!(arr1.includes(val) && arr2.includes(val)))
return val;
});
}
diffArray([1, 2, 3, 7], [3, 2, 1, 4, 5]); // return [7, 4, 5]
또한 화살표 함수 구문을 사용할 수 있습니다.
const diffArray = (arr1, arr2) => arr1.concat(arr2)
.filter(val => !(arr1.includes(val) && arr2.includes(val)));
diffArray([1, 2, 3, 7], [3, 2, 1, 4, 5]); // return [7, 4, 5]
ES2015를 통한 기능적 접근법
의 difference
사이에 은 2개의 중 입니다.Set
운용을 실시합니다. 네이티브가 네이티브임을 있습니다.Set
활자어쨌든 두 집합 간의 차이를 계산할 때는 세 가지 순열이 있습니다.
[+left difference] [-intersection] [-right difference]
[-left difference] [-intersection] [+right difference]
[+left difference] [-intersection] [+right difference]
다음은 이러한 순열을 반영하는 기능적 솔루션입니다.
★★★difference
:
// small, reusable auxiliary functions
const apply = f => x => f(x);
const flip = f => y => x => f(x) (y);
const createSet = xs => new Set(xs);
const filter = f => xs => xs.filter(apply(f));
// left difference
const differencel = xs => ys => {
const zs = createSet(ys);
return filter(x => zs.has(x)
? false
: true
) (xs);
};
// mock data
const xs = [1,2,2,3,4,5];
const ys = [0,1,2,3,3,3,6,7,8,9];
// run the computation
console.log( differencel(xs) (ys) );
difference
:
differencer
그냥 그런 거야differencel
뒤집힌 논쟁으로.를 쓸 수 .const differencer = flip(differencel)
그게 다예요!
칭difference
:
왼쪽과 .difference
사소한 것도 됩니다.
// small, reusable auxiliary functions
const apply = f => x => f(x);
const flip = f => y => x => f(x) (y);
const concat = y => xs => xs.concat(y);
const createSet = xs => new Set(xs);
const filter = f => xs => xs.filter(apply(f));
// left difference
const differencel = xs => ys => {
const zs = createSet(ys);
return filter(x => zs.has(x)
? false
: true
) (xs);
};
// symmetric difference
const difference = ys => xs =>
concat(differencel(xs) (ys)) (flip(differencel) (xs) (ys));
// mock data
const xs = [1,2,2,3,4,5];
const ys = [0,1,2,3,3,3,6,7,8,9];
// run the computation
console.log( difference(xs) (ys) );
이 예는 함수 프로그래밍이 의미하는 바를 이해하기 위한 좋은 출발점이 될 것입니다.
여러 가지 방법으로 함께 연결할 수 있는 구성 요소를 사용하여 프로그래밍합니다.
를 사용한 솔루션indexOf()
스몰 어레이는 괜찮지만, 길이가 길어짐에 따라 알고리즘의 퍼포먼스가 향상됩니다.O(n^2)
오브젝트를 연관지을 수 있는 어레이로 사용하여 어레이 엔트리를 키로 저장함으로써 매우 큰 어레이에서 보다 뛰어난 성능을 발휘하는 솔루션을 다음에 제시합니다.또한 자동으로 중복되는 엔트리는 배제되지만 스트링 값(또는 스트링으로 안전하게 저장할 수 있는 값)에서만 동작합니다.
function arrayDiff(a1, a2) {
var o1={}, o2={}, diff=[], i, len, k;
for (i=0, len=a1.length; i<len; i++) { o1[a1[i]] = true; }
for (i=0, len=a2.length; i<len; i++) { o2[a2[i]] = true; }
for (k in o1) { if (!(k in o2)) { diff.push(k); } }
for (k in o2) { if (!(k in o1)) { diff.push(k); } }
return diff;
}
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
arrayDiff(a1, a2); // => ['c', 'd']
arrayDiff(a2, a1); // => ['c', 'd']
위의 조시벤 포터의 답변은 훌륭하다.그러나 어레이 C에 없는 어레이 B의 요소는 반환되지만 그 반대는 반환되지 않습니다.예를 들어,var a=[1,2,3,4,5,6].diff( [3,4,5,7]);
그러면 다음과 같이 출력됩니다. ==>[1,2,6]
, 그러나 아니다. [1,2,6,7]
이것이 그 둘의 실제 차이입니다.위의 Potter 코드를 그대로 사용할 수 있지만, 다시 한 번 비교하기만 하면 됩니다.
Array.prototype.diff = function(a) {
return this.filter(function(i) {return !(a.indexOf(i) > -1);});
};
////////////////////
// Examples
////////////////////
var a=[1,2,3,4,5,6].diff( [3,4,5,7]);
var b=[3,4,5,7].diff([1,2,3,4,5,6]);
var c=a.concat(b);
console.log(c);
출력은 다음과 같습니다.[ 1, 2, 6, 7 ]
JavaScript의 필터 기능을 갖춘 매우 간단한 솔루션:
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
function diffArray(arr1, arr2) {
var newArr = [];
var myArr = arr1.concat(arr2);
newArr = myArr.filter(function(item){
return arr2.indexOf(item) < 0 || arr1.indexOf(item) < 0;
});
alert(newArr);
}
diffArray(a1, a2);
Array.prototype.difference = function(e) {
return this.filter(function(i) {return e.indexOf(i) < 0;});
};
eg:-
[1,2,3,4,5,6,7].difference( [3,4,5] );
=> [1, 2, 6 , 7]
이거 어때:
Array.prototype.contains = function(needle){
for (var i=0; i<this.length; i++)
if (this[i] == needle) return true;
return false;
}
Array.prototype.diff = function(compare) {
return this.filter(function(elem) {return !compare.contains(elem);})
}
var a = new Array(1,4,7, 9);
var b = new Array(4, 8, 7);
alert(a.diff(b));
하면 .array1.diff(array2)
- x length)라고를 (O(array1.length x array2.length) - O(array1.length x array2.length)이다)
function diffArray(arr1, arr2) {
var newArr = arr1.concat(arr2);
return newArr.filter(function(i){
return newArr.indexOf(i) == newArr.lastIndexOf(i);
});
}
이것은 나에게 효과가 있다.
http://phrogz.net/JS/ArraySetMath.js을 사용하면 다음 작업을 수행할 수 있습니다.
var array1 = ["test1", "test2","test3", "test4"];
var array2 = ["test1", "test2","test3","test4", "test5", "test6"];
var array3 = array2.subtract( array1 );
// ["test5", "test6"]
var array4 = array1.exclusion( array2 );
// ["test5", "test6"]
- 순수 JavaScript 솔루션(라이브러리 없음
- 브라우저와의 ('안 함'('사용 안 함
filter
) - O(n^2)
- 의 「」입니다.
fn
비교 을 지정할 수 callback
function diff(a, b, fn){
var max = Math.max(a.length, b.length);
d = [];
fn = typeof fn === 'function' ? fn : false
for(var i=0; i < max; i++){
var ac = i < a.length ? a[i] : undefined
bc = i < b.length ? b[i] : undefined;
for(var k=0; k < max; k++){
ac = ac === undefined || (k < b.length && (fn ? fn(ac, b[k]) : ac == b[k])) ? undefined : ac;
bc = bc === undefined || (k < a.length && (fn ? fn(bc, a[k]) : bc == a[k])) ? undefined : bc;
if(ac == undefined && bc == undefined) break;
}
ac !== undefined && d.push(ac);
bc !== undefined && d.push(bc);
}
return d;
}
alert(
"Test 1: " +
diff(
[1, 2, 3, 4],
[1, 4, 5, 6, 7]
).join(', ') +
"\nTest 2: " +
diff(
[{id:'a',toString:function(){return this.id}},{id:'b',toString:function(){return this.id}},{id:'c',toString:function(){return this.id}},{id:'d',toString:function(){return this.id}}],
[{id:'a',toString:function(){return this.id}},{id:'e',toString:function(){return this.id}},{id:'f',toString:function(){return this.id}},{id:'d',toString:function(){return this.id}}],
function(a, b){ return a.id == b.id; }
).join(', ')
);
중복되지 않은 2개의 어레이의 차이를 찾으려면:
function difference(arr1, arr2){
let setA = new Set(arr1);
let differenceSet = new Set(arr2.filter(ele => !setA.has(ele)));
return [...differenceSet ];
}
1.difference([2,2,3,4],[2,3,3,4])
[]
2.difference([1,2,3],[4,5,6])
[4,5,6]
3.difference([1,2,3,4],[1,2])
[]
4.difference([1,2],[1,2,3,4])
[3,4]
주의: 위의 솔루션에서는 항상 큰 어레이를 두 번째 파라미터로 전송해야 합니다.절대적인 차이를 찾으려면 먼저 두 배열 중 더 큰 배열을 찾은 다음 작업을 수행해야 합니다.
중복되지 않은 2개의 어레이의 절대적인 차이를 찾으려면:
function absDifference(arr1, arr2){
const {larger, smaller} = arr1.length > arr2.length ?
{larger: arr1, smaller: arr2} : {larger: arr2, smaller: arr1}
let setA = new Set(smaller);
let absDifferenceSet = new Set(larger.filter(ele => !setA.has(ele)));
return [...absDifferenceSet ];
}
1.absDifference([2,2,3,4],[2,3,3,4])
[]
2.absDifference([1,2,3],[4,5,6])
[4,5,6]
3.absDifference([1,2,3,4],[1,2])
[3,4]
4.absDifference([1,2],[1,2,3,4])
[3,4]
두 솔루션의 예 3을 참고하십시오.
오브젝트 리스트가 2개 있는 경우
const people = [{name: 'cesar', age: 23}]
const morePeople = [{name: 'cesar', age: 23}, {name: 'kevin', age: 26}, {name: 'pedro', age: 25}]
let result2 = morePeople.filter(person => people.every(person2 => !person2.name.includes(person.name)))
오래된 어레이와 새로운 어레이를 도입하여 추가된 아이템의 배열과 삭제된 아이템의 배열을 제공하는 유사한 기능을 원했습니다(따라서 .contains!가 포함되지 않음).
제안 솔루션은 이쪽(http://jsbin.com/osewu3/12)에서 이용하실 수 있습니다.
이 알고리즘의 문제나 개선점을 알 수 있는 사람이 있습니까?감사합니다!
코드 리스트:
function diff(o, n) {
// deal with empty lists
if (o == undefined) o = [];
if (n == undefined) n = [];
// sort both arrays (or this won't work)
o.sort(); n.sort();
// don't compare if either list is empty
if (o.length == 0 || n.length == 0) return {added: n, removed: o};
// declare temporary variables
var op = 0; var np = 0;
var a = []; var r = [];
// compare arrays and add to add or remove lists
while (op < o.length && np < n.length) {
if (o[op] < n[np]) {
// push to diff?
r.push(o[op]);
op++;
}
else if (o[op] > n[np]) {
// push to diff?
a.push(n[np]);
np++;
}
else {
op++;np++;
}
}
// add remaining items
if( np < n.length )
a = a.concat(n.slice(np, n.length));
if( op < o.length )
r = r.concat(o.slice(op, o.length));
return {added: a, removed: r};
}
언더스코어.http://http://underscorejs.org/ # intersection 을 사용할 수 있습니다.
어레이에 필요한 메서드:
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]
_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]
이 기능은 동작합니다.기본적으로 2개의 어레이를 Marge하고 중복된 어레이를 찾아 중복되지 않은 어레이를 새로운 어레이에 푸시하는 것이 차이점입니다.
function diff(arr1, arr2) {
var newArr = [];
var arr = arr1.concat(arr2);
for (var i in arr){
var f = arr[i];
var t = 0;
for (j=0; j<arr.length; j++){
if(arr[j] === f){
t++;
}
}
if (t === 1){
newArr.push(f);
}
}
return newArr;
}
//es6 어프로치
function diff(a, b) {
var u = a.slice(); //dup the array
b.map(e => {
if (u.indexOf(e) > -1) delete u[u.indexOf(e)]
else u.push(e) //add non existing item to temp array
})
return u.filter((x) => {return (x != null)}) //flatten result
}
대칭 및 선형 복잡성.ES6가 필요합니다.
function arrDiff(arr1, arr2) {
var arrays = [arr1, arr2].sort((a, b) => a.length - b.length);
var smallSet = new Set(arrays[0]);
return arrays[1].filter(x => !smallSet.has(x));
}
언급URL : https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript
'programing' 카테고리의 다른 글
스프링 컨테이너의 싱글톤 디자인 패턴 vs 싱글톤 원두 (0) | 2022.10.02 |
---|---|
Eclipse를 사용하여 Spring Boot 응용 프로그램을 디버깅하는 방법 (0) | 2022.10.02 |
C#과 Java의 3진 연산자(? :)의 차이 (0) | 2022.10.02 |
pyplot 하위 그림에 대한 공통 축 레이블 (0) | 2022.10.02 |
View의 SELECT는 FROM 절에 하위 쿼리를 포함합니다. (0) | 2022.10.02 |