JavaScript - The Complete Guide 2022

Section 8: Arrays & Iterables - Lists of Data

olivia_yj 2022. 10. 18. 18:48

The goals

💪🏻Different Ways of Creating Arrays

✌🏻Working with Arrays = A Deep Dive!

👍🏻Important Array Methods

👏🏻Other Iterables: Maps & Sets

 

const numbers = [1, 2, 3];
console.log(numbers);

const moreNumbers = new Array(5);
console.log(moreNumbers);

v

 

With this 'new' it can have another characteristic as we can see above.

And we can create an array without 'new' keyword, but still it works the same

 

 

Array Methods

push()

pop()

unshift()

shift()

splice()

slice()

concat()

indexOf()

lastIndexOf()

includes()

find()

findindex()

forEach()

map()

reverse()

filter()

reduce()

split()

join()

set()

 

JavaScript에서 메서드 체인 형성하기

지금까지 배운 모든 유용한 배열 메서드를 결합하는 방법을 이해하는 것이 중요합니다. map()과 reduce() 를 예로 들어 보겠습니다.

  1. const originalArray = [{price: 10.99}, {price: 5.99}, {price: 29.99}];
  2. const transformedArray = originalArray.map(obj => obj.price); // produces [10.99, 5.99, 29.99]
  3. const sum = transformedArray.reduce((sumVal, curVal) => sumVal + curVal, 0); // => 46.97

물론 map 단계를 건너뛰고 추출 로직을 reduce()에 추가하셔도 됩니다.

  1. const originalArray = [{price: 10.99}, {price: 5.99}, {price: 29.99}];
  2. const sum = originalArray.reduce((sumVal, curVal) => sumVal + curVal.price, 0); // => 46.97

하지만 더 복잡한 추출 논리가 있어, 여러 개의 메서드 호출로 분할하려고 한다고 해보겠습니다. 또는 애플리케이션의 여러 다른 위치에서 재사용 가능한 map 함수가 있다고 해보죠. 그러면 메서드 체인을 활용하면 첫 번째 예제를 더 간결하게 작성할 수 있습니다.

  1. const originalArray = [{price: 10.99}, {price: 5.99}, {price: 29.99}];
  2. const sum = originalArray.map(obj => obj.price)
  3. .reduce((sumVal, curVal) => sumVal + curVal, 0); // => 46.97

map() 의 결과에서 직접 .reduce() 를 호출합니다(배열을 생성하므로 이를 가능하게 합니다). 따라서 매핑된 배열을 다른 곳에서는 필요하지 않은 상수나 변수에 별도로 저장하지 않을 수 있습니다.

 

JavaScript Sets

A JavaScript Set is a collection of unique values.

Each value can only occur once in a Set.

A Set can hold any value of any data type.

How to Create a Set

You can create a JavaScript Set by:

  • Passing an Array to new Set()
  • Create a new Set and use add() to add values
  • Create a new Set and use add() to add variables

 

WeakMap and WeakSet

As we know from the chapter Garbage collection, JavaScript engine keeps a value in memory while it is “reachable” and can potentially be used.

For instance:

let john = { name: "John" };

// the object can be accessed, john is the reference to it

// overwrite the reference
john = null;

// the object will be removed from memory

Usually, properties of an object or elements of an array or another data structure are considered reachable and kept in memory while that data structure is in memory.

For instance, if we put an object into an array, then while the array is alive, the object will be alive as well, even if there are no other references to it.

Like this:

let john = { name: "John" };

let array = [ john ];

john = null; // overwrite the reference

// the object previously referenced by john is stored inside the array
// therefore it won't be garbage-collected
// we can get it as array[0]

Similar to that, if we use an object as the key in a regular Map, then while the Map exists, that object exists as well. It occupies memory and may not be garbage collected.

For instance:

let john = { name: "John" };

let map = new Map();
map.set(john, "...");

john = null; // overwrite the reference

// john is stored inside the map,
// we can get it by using map.keys()

WeakMap is fundamentally different in this aspect. It doesn’t prevent garbage-collection of key objects.

Let’s see what it means on examples.

WeakMap

The first difference between Map and WeakMap is that keys must be objects, not primitive values:

let weakMap = new WeakMap();

let obj = {};

weakMap.set(obj, "ok"); // works fine (object key)

// can't use a string as the key
weakMap.set("test", "Whoops"); // Error, because "test" is not an object

Now, if we use an object as the key in it, and there are no other references to that object – it will be removed from memory (and from the map) automatically.

let john = { name: "John" };

let weakMap = new WeakMap();
weakMap.set(john, "...");

john = null; // overwrite the reference

// john is removed from memory!

Compare it with the regular Map example above. Now if john only exists as the key of WeakMap – it will be automatically deleted from the map (and memory).

WeakMap does not support iteration and methods keys(), values(), entries(), so there’s no way to get all keys or values from it.

WeakMap has only the following methods:

  • weakMap.get(key)
  • weakMap.set(key, value)
  • weakMap.delete(key)
  • weakMap.has(key)

Why such a limitation? That’s for technical reasons. If an object has lost all other references (like john in the code above), then it is to be garbage-collected automatically. But technically it’s not exactly specified when the cleanup happens.

The JavaScript engine decides that. It may choose to perform the memory cleanup immediately or to wait and do the cleaning later when more deletions happen. So, technically, the current element count of a WeakMap is not known. The engine may have cleaned it up or not, or did it partially. For that reason, methods that access all keys/values are not supported.

 

 

 

 

 

 

 

 

 

 

 

Sources

https://www.w3schools.com/js/js_object_sets.asp

 

JavaScript Sets

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com