iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 28
0
Modern Web

從Stack Overflow學前端系列 第 28

從StackOverflow上學CODING(28) 判斷兩個陣列中的不同點

How to get the difference between two arrays in JavaScript?

Is there a way to return the difference between two arrays in JavaScript?
有沒有方法可以return兩個不同陣列中不同的點?
For example:

var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];

// need ["c", "d"]

Array.prototype.diff = function(a) {
    return this.filter(function(i) {return a.indexOf(i) < 0;});
};

////////////////////  
// Examples  
////////////////////

[1,2,3,4,5,6].diff( [3,4,5] );  
// => [1, 2, 6]

["test1", "test2","test3","test4","test5","test6"].diff(["test1","test2","test3","test4"]);  
// => ["test5", "test6"]

上一篇
從StackOverflow上學CODING(27) JS return多個值
下一篇
從StackOverflow上學CODING(29) 如何監聽判斷enter鍵?
系列文
從Stack Overflow學前端30

尚未有邦友留言

立即登入留言