---
description: 善用 array.filter 特性
---

# # 1002 Find Common Characters

[LeetCode](https://leetcode.com/problems/find-common-characters/)

```
Given an array A of strings made only from lowercase letters, 
return a list of all characters that show up in all strings within the list 
(including duplicates).  
For example, if a character occurs 3 times in all strings but not 4 times, 
you need to include that character three times in the final answer.

You may return the answer in any order.

input: 給一小寫字串陣列
output: 找出相同的字母
```

```
Example 1:

Input: ["bella","label","roller"]
Output: ["e","l","l"]
Example 2:

Input: ["cool","lock","cook"]
Output: ["c","o"]
 

Note:

1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j] is a lowercase letter

/**
 * @param {string[]} A
 * @return {string[]}
 */
var commonChars = function(A) {
    
};
```

### 怎麼解

第一想法會是一個一個找兩個 for 迴圈

```
var commonChars = function(A) {
  // ["b", "e", "l", "l", "a"]
  let pointer = A[0].split('');
  for(let i = 1; i< A.length; i++){
    // tempChar = ["r", "o", "l", "l", "e", "r"]
    let tempChar = A[i].split('');
    pointer = pointer.filter( char => {
      // 1. char = "b", ind = -1 , can't find in tempChar, so pointer [false, "e", "l", "l", "a"]  false not return in array so is ["e", "l", "l", "a"]
      // 2. char = "e", ind = 4, pointer = ["e", "l", "l", "a"], tempChar = ["r", "o", "l", "l", true, "r"]
      // 3. char = "l", ind = 2, pointer = ["e", "l", "l", "a"], tempChar = ["r", "o", true, "l", true, "r"]
      // 4. char = "l", ind = 3, pointer = ["e", "l", "l", "a"], tempChar = ["r", "o", true, true, true, "r"]
      // 5. char = "a", ind = -1, pointer = ["e", "l", "l"], tempChar = ["r", "o", true, true, true, "r"]
      let ind = tempChar.indexOf(char);
      return ind != -1 ? tempChar[ind] = true : false
    })
    
  }
  return pointer;
}
// faster than 85.85% of JavaScript
```

###

我會用 map 先記字母然後幾次
