복습 #3-2 배열 (Array)

Joshua Song / 송성현·2019년 11월 19일
0

프리코스_35

목록 보기
8/15

Introduction

지난 포스팅에 이어지는 배열 method 복습 파트 2이다. 바로 시작하자.

배열에 요소를 추가 / 제거

(array.push / array.unshift / array.pop / array.shift)

array.push(obj)는 mutable이다. 배열의 맨끝에 새로운 요소들을 추가한 후 새로운 길이를 반환한다.


Example) 

let animal = ['pigs', 'goats', 'sheep'];

let count = animals.push('cows');

console.log(count);

// expected output: 4

console.log(animals);

// expected output: Array ["pigs", "goats", "sheep", "cows"]

array.unshift(obj)는 mutable 인데 배열의 맨앞에 새로운 요소들을 추가한 후 새로운 길이를 반환한다.

Example)

var array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));

// expected output: 5

console.log(array1);

// expected output: Array [4, 5, 1, 2, 3]

array.pop(obj)는 mutable 인데 배열의 맨마지막에 있는 요소를 제거한 뒤 제거된 요소를 반환한다. 배열의 길이도 바꾼다.


Example)

var plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());

// expected output: "tomato"

console.log(plants);

// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

array.shift(obj)는 mutable인데 배열의 맨앞에 있는 요소를 제거한 뒤 제거된 요소를 반환한다. 배열의 길이도 바꾼다.


Example)

var array1 = [1, 2, 3];

var firstElement = array1.shift();

console.log(array1);

// expected output: Array [2, 3]

console.log(firstElement);

// expected output: 1

배열의 원하는 인덱스부터 인덱스까지의 요소를 추출하기

(array.slice(starting index, ending index)) *immutable

argument로는 첫번째 index 아니면 첫번째와 마지막 index 둘다가 들어갈 수 있다. index의 범위만큼 element를 추출한 후 새로운 배열을 반환하기 때문에 배열을 복사할 때 유용하다.

첫번 째 index 부터지만 마지막 index의 element는 포함하지 않고 딱 그전까지만 복사를 한다. 마지막 index값이 생략되거나 배열의 길이보다 길다면 끝까지 복사를 한다. 음수일 경우 배열의 끝에서부터 시작해 처음 index를 설정한다.

첫번째 index가 undefined이면 0부터 시작하고, 첫번째 index가 길이보다 크다면 빈 배열을 반환한다.


Example)


var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));

// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));

// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));

// expected output: Array ["bison", "camel", "duck", "elephant"]

하...indexOf까지 오랫동안 정리했는데 저장안해서 다 날라갔다...그래도 개인적인 공부는 했으니 포스팅은 간단하게하기로...열받는다...!

배열의 기존 요소를 제거하거나 추가

(array.splice (index, number of element to delete, element to add))

(mutable) splice는 배열에 있어 요소를 제거하거나 추가할 때 사용된다.


Example)

var months = ['Jan', 'March', 'April', 'June'];

months.splice(1, 0, 'Feb');

// inserts at index 1

console.log(months);

// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']

months.splice(4, 1, 'May');

// replaces 1 element at index 4

console.log(months);

// expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']

배열에 함수를 실행한 후 하나의 결과값을 반환할 때

(Array.reduce ( function(acc, cur, idx, src){callback}, initial value)

  • acc는 누적되는 값이다. initial value가 지정되지 않았을 경우 첫번째 index의 element이다.
  • cur는 처리할 첫번째 요소이다.
  • idx는 처리할 요소의 index이다.
  • src 는 reduce()를 호출한 배열이다.

사실 일일히 reduce의 다양한 사용법과 example까지 엄청 공을 들여 설명했는데 실수로 창을 닫아 다 날라갔다...그러므로 그냥 mdn의 example을 가져오겠다...다시 다 쓸 자신은 없다.

배열의 모든 값 합산

var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);
// sum is 6
객체 배열에서의 값 합산
객체로 이루어진 배열에 들어 있는 값을 합산하기 위해서는 반드시 초기값을 주어 각 항목이 여러분의 함수를 거치도록 해야 합니다.

var initialValue = 0;
var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) {
    return accumulator + currentValue.x;
},initialValue)

console.log(sum) // logs 6
중첩 배열 펼치기flatten
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  function(accumulator, currentValue) {
    return accumulator.concat(currentValue);
  },
  []
);
// 펼친 결과: [0, 1, 2, 3, 4, 5]
객체 내의 값 인스턴스 개수 세기
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

var countedNames = names.reduce(function (allNames, name) { 
  if (name in allNames) {
    allNames[name]++;
  }
  else {
    allNames[name] = 1;
  }
  return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

이정도가 흔히, 또 많이 사용되는 reduce 사용법이다.

배열의 요소들을 연결해 string으로 변환할 때

(Array.join(separator))

string의 split과는 반대인 join이다. join 속 separator는 배열의 요소들을 이어줄 문자열이다. 생략할 경우 쉼표로 이어지고 빈 문자열이면 사이에 아무 문자도 없이 이어진다. 배열의 길이가 0 이면 빈 배열을 반환한다.

Example)

var elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

console.log(elements.join(''));
// expected output: "FireAirWater"

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"

배열의 요소를 찾거나 있는지 없는지 확인할 때

(Array.indexOf(element, fromindexof), Array.includes(element, fromindexof), Array.find(callback))

  • indexOf는 찾고자하는 요소가 배열에 있는지 확인하고 있을 시 그 요소의 index를 반환한다. 없을 시 -1을 반환하고 fromindexof는 몇번 째 index부터 찾으라고 설정해주는 것이다.

  • includes는 찾고자하는 요소가 배열에 있을 시 true, 없을 시 false를 반환한다. fromindexof는 indexOf처럼 어디 index부터 찾아보라 설정해준다.

  • find는 callback에 해당되는 요소가 배열에 있는지 확인하고 있을 시 해당되는 첫번 째 요소를 반환한다. 없으면 undefined이다. callback은 3개의 인자를 받는데,

element, index, 그리고 array를 받는다.

Example #indexOf)

var beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));

// expected output: 1

// start from index 2

console.log(beasts.indexOf('bison', 2));

// expected output: 4

Example #includes)

var array1 = [1, 2, 3];

console.log(array1.includes(2));

// expected output: true

Example #find)

var array1 = [5, 12, 8, 130, 44];

var found = array1.find(function(element, index, array) {

  return element > 10;

});

console.log(found);

// expected output: 12

배열끼리 연결해 줄 때

(Array1.concat(Array2))
flatten할 때 자주 쓰이는 이 method는 간단하다. Example을 통해 보겠다.

Example)
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];

console.log(array1.concat(array2));
// expected output: Array ["a", "b", "c", "d", "e", "f"]

배열안의 요소가 판별함수를 통과하는지 볼 때

(Array.every() , Array.some())
every는 모든 요소가 통과하는지 안하는지 보고 some은 몇개의 요소라도 통과하는지를 본다.
통과할 경우 true, 아닐 경우 false이다. 하지만 빈 배열에서 호출할 경우 every는 true, some은 false를 반환한다.

Example #every, some)
function isBelowThreshold(currentValue) {
  return currentValue < 40;
}

var array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true
console.log(array1.some(isBelowThreshold));
//expected output: true

배열을 한 값으로 채울 때

(Array.fill(value, starting index, ending index))

starting index와 ending index는 optional이다. from starting index and until ending index이기 때문에 ending index보다 하나 전까지이다. 이 method는 example을 보는게 가장 빠르다.


Example)

var array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4

console.log(array1.fill(0, 2, 4));

// expected output: [1, 2, 0, 0]

// fill with 5 from position 1

console.log(array1.fill(5, 1));

// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));

// expected output: [6, 6, 6, 6]

배열의 순서를 반전할 때

(Array.reverse()) *mutable
타이틀 그대로 순서를 반전하는데 원래 기본 배열에 변화를 줄 수 있다.

Example)

var array1 = ['one', 'two', 'three'];
var reversed = array1.reverse(); 
console.log('reversed: ', reversed);
// expected output: Array ['three', 'two', 'one']

정렬 후 배열을 반환

(array.sort(Callback)) *mutable

기본적으로 sort는 문자열의 유니코드 포인트에 따라 정렬을 한다. 따라서 array.sort()는 원하는 값을 주지 않을 수 있다. 그러므로 정렬 순서를 정의하는 함수를 짜주는게 가장 좋다. sort를 사용하는 방법은 무수히 많지만, 정렬 순서를 정하는 함수를 짜주고 사용했을 때가 가장 유용한것 같다.

Example)

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);

// [1, 2, 3, 4, 5]
profile
Grow Joshua, Grow!

0개의 댓글