[Javascript] Array Methods

Suyeon·2020년 8월 28일
0

Javascript

목록 보기
9/31

Stack

  • Stacks are data structures that follow the “last-in-first-out” or “LIFO” paradigm.
  • JavaScript doesn’t provide a native stack data structure, so we have to build our own with an array and a closure or a class.
  • pop(), push()

Queue

  • Queues use the “first-in-first-out” or “FIFO” method.

Add/Remove items

// Add
arr.push(...items) 
arr.unshift()
arr.concat(arg) // return new array

// Remove
arr.pop() 
arr.shift() 
arr.splice() // Mutate original array
arr.slice() // return new array

Iterate

// (1) for...of loop
for (const el of arr) {
  console.log(element);
}

// (2) forEach
arr.forEach(function(item, index, array) {
  // ... 
});

Searching in array

// (1) indexOf and includes
let arr = [1, 0, false];

alert( arr.indexOf(0) ); // 1
alert( arr.includes(1) ); // true

// (2) find and findIndex
let users = [
  {id: 1, name: "John"},
  {id: 2, name: "Pete"},
  {id: 3, name: "Mary"}
];

let user = users.find(item => item.id == 1);
let userIndex = users.findIndex(item => item.id == 1);

alert(user.name); // John
alert(userIndex); // 0

// (3) filter
let someUsers = users.filter(item => item.id < 3);
alert(someUsers.length); // 2

Transform

// (1) map
let lengths = ["Bilbo", "Gandalf", "Nazgul"].map(item => item.length);
alert(lengths); // 5,7,6

// (2) sort
let arr = [ 1, 2, 15 ];

// arr.sort(): 1, 15, 2
arr.sort((a, b) => a - b);  // 1, 2, 15

countries.sort((a, b) => a.localeCompare(b)); // Andorra,Österreich,Vietnam (correct!)

// (3) reverse
let arr = [1, 2, 3, 4, 5];
arr.reverse(); // 5,4,3,2,1

// (4) split and join
let arr = 'a, b, c, d';
arr.split(', '); // ['a', 'b', 'c', 'd']

let str = "test";
str.split(''); // t,e,s,t

let arr= ['a', 'b', 'c', 'd'];
arr.join(';'); // 'a;b;c;d'

// (5) reduce
let arr = [1, 2, 3, 4, 5];

let result = arr.reduce((sum, current) => sum + current, 0);
alert(result); // 15
profile
Hello World.

0개의 댓글