웹개발/혼자하는 개발 공부

[자바스크립트] Simple Array Methods

데브리 2021. 9. 16. 06:08

 

.slice

extract part of any array without changing the original array

 

let arr = ['1', '2', '3', '4', '5']
console.log(arr.slice(2));     // ['3', '4', '5']
console.log(arr.slice(2,4));   // ['3', '4']
console.log(arr.slice(-2));   // ['4', '5']

 

 

 

 

.splice

필요없는 element를 제외시킬 때 유용하다.

change the content of an array by removing or replacing existing elements and / or adding new elements. 

 

console.log(arr.splice(2));   // ['1','2']
console.log(arr);   // ['1','2']

 

 

 

 

.reverse

array 순서 역으로 바꾸기

actually mutate the original array

 

const arr2= ['6','7','8','9','10'];
console.log(arr2.reverse());   // ['10','9','8','7','6']

 

 

 

 

.concat

concatenate(사슬같이 잇다, 연쇄시키다) two arrays

 

const num_array = arr.concat(arr2);
console.log(num_array);


혹은


console.log([...arr, ...arr2]);

 

 

 

 

 

.join 

 

console.log(arr.join(' - ');
// a - b - c - d - e

 

 

 

 

forEach

loop over the array, and in each interation it will execute the callback function. 

 

 

for loop vs forEach

차이점? You cannot break out of a forEach loop.

const movements = [200, 450, -400, 3000, -650, -130, 70, 1300];
// for loop
for (const movement of movements) {
  if (movement > 0) {
    console.log(`You deposited ${movement}`);
  } else {
    console.log(`You withdrew ${movement}`);
  }
}

// forEach
movements.forEach(function (mov, i, arr) {    
         // 1st element(mov): current element, 2nd(i): current index, 3rd(arr): entire array  
  if (mov > 0) {
    console.log(`You deposited ${mov}`);
  } else {
    console.log(`You withdrew ${Math.abs(mov)}`);
  }
});

// 0: function(200)
// 1: function(450)
// ...

 

 

 

 

 

.entries

returns an array of arrays

for (const [i], movement] of movements.entries()) {
}
// 1st position([i]): current index, 2nd position(movement): current array element

 

 

 

 

Math.abs

returns the absolute value

 

 

 

 

 

forEach with Maps and Sets

 

with Map

const currencies = new Map([
  ['USD', 'United States dollar'],
  ['EUR', 'Euro'],
  ['GBP', 'Pound sterling'],
]);

currencies.forEach(function(value, key, map) {
  console.log(`${key}:${value}`);
})

// 
USD:United States dollar
EUR:Euro
GBP:Pound sterling

 

 

 

with set

const currenciesUnique = new Set(['USD', 'GBP', 'USD', 'EUR', 'EUR']);
console.log(currenciesUnique);
currenciesUnique.forEach(function (value, _, map) {
  console.log(`${value}:${value}`);
});

// set doesn't have keys and indexes
USD:USD
GBP:GBP
EUR:EUR

 

 

 

 

Creating DOM Elements

 

global variables, start passing the data into a function 보다는 pass the data into a funciton이 더 좋은 연습방법. 

 

 

 

 

 

.insertAdjacentHTML

Interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.

element.insertAdjacentHTML(position, text);

 

 

 

 

 

.innerHTML

text content simply returns the text itself, but innerHTML retures everything including all the html tags.

 

 

 

 

 

 

map, filter, reduce

 

 

 

 

 

How to get the first letter of a word

const user = 'James Tim Cindy';   // jtc
const username = user
  .toLowerCase()
  .split(' ')               // divide the string into words
  .map(name => name[0])
  .join(' ');

console.log(username);

 

 

 

 

 

Chaining Methods

// PIPELINE
const totalDepositsUSD = movements.
  .filter(mov => mov < 0)       
  .map((mov, i, arr) => {       // the result of the previous operation, not the initial movements array
    console.log(arr);
    return move * eurToUsed;
  })
// .map(mov => mov * acc + mov, 0);
console.log(totalDepositsUSD);

1. overusing chaining can cause real performoance issues if we have huge arrays.

If we have a huge array, we should try to compress all the funcionality that they do into as little methods as possible.

2. It is a bad practice in JavaScript to chain methods that mutate the underlying original array.

 

 

 

 

 

.find

retrieve(되찾다, 검색하다) one element of an array based on a condition

보통 원하는 하나의 element를 찾기위한 목적으로 많이 쓰임

const account = accounts.find(acc => acc.owner === 'Jessica');

the Find method is similar to the Filter method, but

1. Filter returns all the elements that match the condition while the Find method only returns the first one

2. Filter returns a new array while Find only returns the element itself, not an array

 

 

 

 

 

.findIndex

return the index of the found element not the element ifself

 

.preventDefault

prevent HTML's default behaviours

 

 

 

 

 

.some

return true if at least one of elemnts in the array satisties the condition

.every

: only return true if all of the elements in the array satisfy the condition we pass in.

.flat

const arr = [[1, 2, 3], [4, 5, 6], 7, 8];
console.log(arr.flat());     // [1, 2, 3, 4, 5, 6, 7, 8] this goes one level deep

const arrDeep = [[[1, 2], 3], [4, [5, 6]], 7, 7];
console.log(arr.flat(2));    // [1, 2, 3, 4, 5, 6, 7, 8]

 

 

 

 

.flatMap

(map + flat)

: combine a map and a flat method into one method.

flatmap method only goes one level deep

sorting arrays

const owners = ['Jonas', 'Zach', 'Adam', 'Marta']
console.log(owners.sort());     // ["Adam", "Jonas", "Marta", "Zach"]

It converts everyhing to strings, so doesn't work properly for numbers

 

const n = [200, 450, -400, 3000, -650, -130, 70, 1300];

// Ascending 오름차순
n.sort((a, b) => {
  if (a > b) return 1;
  if (a < b) return -1;
});

한줄로 바꾸면
n.sort((a, b) => a - b);

console.log(n);       // [-650, -400, -130, 70, 200, 450, 1300, 3000]


// Descending 내림차순
n.sort((a, b) => {
  if (a > b) return -1;
  if (a < b) return 1;
});

한줄로 바꾸면
n.sort((a, b) => b - a);

console.log(n);       // [3000, 1300, 450, 200, 70, -130, -400, -650]

 

 

 

 

.fill

// Empty Arrays + fill method
const x = new Array(7);
console.log(x);  //  (7) [empty x 7]

x.fill(1);
console.log(x)    // (7) [1, 1, 1, 1, 1, 1, 1]

 

 

 

 

Array.from

create arrays from other things (array-like structures)

const y = Array.from({length: 7}, () => 1);
console.log(y)     // (7) [1, 1, 1, 1, 1, 1, 1]

const z = Array.from({length: 7}, (_, i) => i + 1);
console.log(z)    // (7) [1, 2, 3, 4, 5, 6, 7]

 

 

 

 

 

Prefixed ++ operator

let a = 10;
console.log(++a);     // 11
console.log(a);       // 11