LeetCode — JavaScript Challenge 30 Days — Array

TH K
5 min readJun 6, 2023

--

做了好幾次人格測驗都是 ISTP ,確實幾乎每個特質都解析的很正確,但有一點我不同意,我喜歡看別人玩極限,但是我不敢,我怕爆~

JS 30 第二個主題 Array,這個主題有一點難寫因為知識點很多然後又零碎,主要任務是用 code 寫出常用的 array method — map, filter, reduce。

迭代

首先他們有共同的特性就是需要去迭代 array,迭代 array 可以分成使用for loop, for…of…, for…in…, Array.prototype.forEach(), 以做出map() 為例

值得注意的是 for…in…對於 sparse array 的操作,其實是跟 JS 提供的 array method 是一樣的會去忽略空值(注意這裡的空值不是指 null ! ),運行速度不是最快但是也是最接近 JS 提供的 array method。

記憶體

除了迭代的方法,這幾個 method 都是屬於 return 一個新的 array ,所以以上方法都有先在 function 裡建立一個新的 array,然而沒有給定 array 的長度是會影響效能的,因為如果建立未定長度的 array ( let arr = [] )每一次的新增跟刪除都會需要去動態調整記憶體分配,所以在未來array的操作如果已知array操作長度可以用 ( let arr = new Array( length ) )先將記憶體分配寫好。

Arrays in JavaScript are dynamic, which means they can grow or shrink in size dynamically. When elements are added to an array, JavaScript automatically allocates memory to accommodate the new elements. Similarly, when elements are removed from an array, JavaScript frees up the memory previously allocated to those elements.

Array 這個資料型別通常是儲存於記憶體中連續位置,當對他的儲存長度做更動時就會需要整份移到放得下的地方,還有就是通常 array 的儲存是一串固定大小的東西,如果放滿的狀況下又新增一個元素進去,他會在挪出一段固定大小的記憶體空間分配給 array ,你的 array 長度大小可能不能代表實際上存在記憶體中的大小,詳細連結

結論,為了效能跟記憶體分配 ,在處理大量資料時,能預先建好array的空間分配是最好的。

Array.prototype.reduce()

reduce 算是我在學習中比較少用到的 method,主要是很少想到怎麼用它,其中一個好的應用是當你發現你會需要操作一個陣列同時需要 map 跟 filter時,就使用reduce 這樣big O 從 2n → n 節省效能 。

const groceries = [
{ id: 173, name: "Soup" },
{ id: 964, name: "Apple" },
{ id: 535, name: "Cheese" }
];

/** With filter and map */
var names = groceries
.filter(item => item.id > 500)
.map(item => item.name)

/** With reduce */
var names = groceries.reduce((accumulator, val) => {
if (val.id > 500) {
accumulator.push(val.name);
}
return accumulator;
}, []);

console.log(names); // ["Apple", "Cheese"]

然後 reduce 除了運算上的累加也可以用於轉置 array 或 object,非常實用。

const groceries = [
{ id: 173, name: "Soup" },
{ id: 964, name: "Apple" },
{ id: 535, name: "Cheese" }
];

const indexedGroceries = groceries.reduce((accumulator, val) => {
accumulator[val.id] = val;
return accumulator;
}, {});

console.log(indexedGroceries);
/**
* {
* "173": { id: 173, name: "Soup" },
* "964": { id: 964, name: "Apple" },
* "535": { id: 535, name: "Cheese" },
* }
*/

ref: MDN, Apply Transform Over Each Element in Array, Filter Elements from Array, Array Reduce Transformation

--

--