# Array Method

範例在此，[it 邦](https://ithelp.ithome.com.tw/articles/10213787)

| **Method**                            | **原本陣列** | **return**                                                                     |
| ------------------------------------- | -------- | ------------------------------------------------------------------------------ |
| **Basic Array Method**                |          |                                                                                |
| push(ele)                             | Array 改變 | Number (length)                                                                |
| unshift(ele)                          | Array 改變 | Number (length)                                                                |
| pop()                                 | Array 改變 | 被移掉的那個值                                                                        |
| shift()                               | Array 改變 | 被移掉的那個值                                                                        |
| concat()                              | 不變       | Array                                                                          |
| **Filter something**                  |          |                                                                                |
| findIndex(callback)                   | 不變       | Number                                                                         |
| find(callback)                        | 不變       | 第一個找到的 "值"                                                                     |
| filter(callback)                      | 不變       | 符合條件的 Array                                                                    |
| forEach(callback)                     | Array 改變 | undefined                                                                      |
| map(callback)                         | 不變       | 數量為 array.length 的 Array                                                       |
| some(callback)                        | 不變       | Boolean                                                                        |
| every(callback)                       | 不變       | Boolean                                                                        |
| **Special**                           |          |                                                                                |
| reduce(acc, cur)                      | 不變       | 值                                                                              |
| **Order**                             |          |                                                                                |
| sort()                                | Array 改變 | 數量為 array.length 的 Array                                                       |
| toSorted()                            | 不變       |                                                                                |
| reverse()                             | Array 改變 | 數量為 array.length 的 Array                                                       |
| toReversed()                          | 不變       |                                                                                |
| **Operation**                         |          |                                                                                |
| slice(start, end)                     | 不變       | return 包含 start 不包含 end 的 Array                                                |
| splice(start, deleteCount, insert)    | Array 改變 | 回傳移掉的值 Array                                                                   |
| toSpliced(start, deleteCount, insert) | 不變       | 回傳結果Array                                                                      |
| indexOf(ele)                          | 不變       | 所在位置 Number                                                                    |
| join()                                | 不變       | String                                                                         |
| includes(ele)                         | 不變       | Boolean                                                                        |
| flat(\[depth])                        | 不變       | <p>const arr1 = \[0, 1, 2, \[3, 4]];</p><p>arr1.flat() // \[0, 1, 2, 3, 4]</p> |

## Immutable way

```
const [tasks, setTasks] = useState([
    { id: 0, content: "Walk the dog" },
    { id: 1, content: "Water the plants"},
    { id: 2, content: "Wash the dishes" },
]);
```

<table><thead><tr><th width="105">method</th><th width="96">use</th><th></th></tr></thead><tbody><tr><td>Add</td><td>concat</td><td><pre><code><strong>tasks.concat({ 
</strong><strong>    id: Date.now().toString(), content: 'xx', 
</strong><strong>})
</strong></code></pre><pre class="language-javascript"><code class="lang-javascript">[{ 
    id: Date.now().toString(), 
    content: value.trim() 
}, ...tasks]
</code></pre></td></tr><tr><td>Delete</td><td>filter</td><td><pre><code>tasks.filter((task, i) => i !== index)
</code></pre></td></tr><tr><td></td><td></td><td></td></tr></tbody></table>

## 其他常用

<table><thead><tr><th width="247">Method</th><th width="108">判斷是否為 Array</th><th>Example</th></tr></thead><tbody><tr><td>Array.isArray()</td><td>判斷是否為 Array</td><td>Array.isArray([]) // true<br>Array.isArray("[]") // false</td></tr><tr><td>Array.from({ length: 5 })</td><td></td><td>Array.from({ length: 5 }). // [undefined, undefined...]. 總共五個</td></tr><tr><td>Array.from ({ length: 5 }, fn)</td><td></td><td>Array.from({length: 3}, () => Array(2).fill(0)) //<br>[  [0,"0], [0,0], [0,0] ]<br>Array.from({length: 3}, (_, i) => i + 1) // [1,2,3]</td></tr><tr><td>[ arr1, arr2 ] = [ arr2, arr1 ]</td><td>交換位置</td><td><p>let arr = [1,2,3]</p><p><code>[ arr[0], arr[2] ] = [ arr[2], arr[0] ]</code><br>// [3,2,1]</p></td></tr><tr><td>arr[i] = arr[len -1]<br>arr.pop()</td><td>把算過丟到最後然後 pop()</td><td>[1,2,3] 移掉 1</td></tr><tr><td>Object.fromEntries</td><td>把 array 變回 object</td><td>Object.fromEntries([[0,'a'], [1,'b']]) // [{0: 'a', 1: 'b'}</td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr></tbody></table>

## Reimplement the `Array` method

### Array.map

```javascript
/**
 * @param {number[]} arr
 * @param {Function} fn
 * @return {number[]}
 */
var map = function(arr, fn) {
    var result = [];
    for( let [index, value] of arr.entries()){
      result[index] = fn(value, index)
    }
    return result;
};
```

### Array.filter

```javascript
/**
 * @param {number[]} arr
 * @param {Function} fn
 * @return {number[]}
 */
var filter = function(arr, fn) {
    let result = [];
    let size = 0
    for(let [i, value] of arr.entries()) {
         if(fn(value, i)){
           result[size] = value
           size++;
         }
    }
    return result;
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hannahpun.gitbook.io/leetcode-note/tools/array-method.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
