DAY 14
0

# 今日kata

Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.

`````` [1,2],[1] ==> [2]
[1,2,2,2,3],[2] ==> [1,3]
``````

## 構想&解法

``````function arrayDiff(a, b) {
if (a.length === 0 || b.length == 0) {
return a
} else {
let result = a
b.forEach(removeItem => result = result.filter(item => item === removeItem ? '' : item.toString()))
return result
}
}
``````

a減去b:

• a或b為空時，代表沒有東西要減或是被減，回傳a陣列。
• forEach遍歷每一個b中的元素`removeItem`，檢查a中每一個元素`item`是不是等於`removeItem`，不等於就留下!

## 其他解法觀摩

``````function array_diff(a, b) {
return a.filter(e => !b.includes(e));
}
``````

`arr.includes(searchElement)`這個方法會檢查arr中是否有searchElement的存在，結果會回傳true或false。

arr.includes() IE不支援....可以採用下面for loop+indexOf()的寫法

``````function array_diff(a, b) {
var arr = new Array();
for(var i = 0;i<a.length;i++){
if(b.indexOf(a[i])<0){
arr.push(a[i]);
}
}
return arr;
}
``````

## 整理用法

### 陣列的交集、差集

Intersection(交集):

``````let intersection = arr1.filter(x => arr2.includes(x));
``````

Difference(差集):

``````let difference = arr1.filter(x => !arr2.includes(x));
``````