문제풀이 Feedback/Javascript

배열 매소드(Array method)

1. Mutable
 - Fill, copywithin, sort, reverse, splice, pop, shift, unshift

2. Immutable
 - concat, filter, find, forEach, findindex, includes, indexOf, join, lastindexOf, map, reduceright, slice
   some, every

  • concat()인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환합니다.  - 원본 배열을 변경하지 않습니다
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]
  • copyWithin()배열의 일부를 얕게 복사한 뒤, 동일한 배열의 다른 위치에 덮어쓰고 그 배열을 반환합니다.  - 원본 배열을 변경합니다
const array1 = ['a', 'b', 'c', 'd', 'e'];

// copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// expected output: Array ["d", "b", "c", "d", "e"]

// copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// expected output: Array ["d", "d", "e", "d", "e"]
  • entries()배열의 각 인덱스에 대한 키/값 쌍을 가지는 새로운 배열 반복자 객체를 반환합니다.  - 원본 배열을 변경하지 않습니다
const array1 = ['a', 'b', 'c'];
const iterator1 = array1.entries();
for(let e of iterator1){
console.log(e)
}
//> Array [0, "a"]
//> Array [1, "b"]
//> Array [2, "c"]
  • every()배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트합니다.만약 배열의 모든 요소가 제공된 판별 함수를 통과하면 true를 반환합니다.  - 빈 배열에서 호출하면 무조건 true를 리턴합니다. - every는 호출한 배열을 변형하지 않습니다.
const array1 = [30, 39, 29, 10, 13];
console.log(array1.every(elem => elem >= 10));
// expected output: true
  • fill()배열의 시작 인덱스부터 끝 인덱스의 이전까지 정적인 값 하나로 채웁니다.  - 원본 배열을 변경합니다
const 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]
  • filter()주어진 함수의 테스트를 통과하는(결과가 참인 경우의) 요소들을 모아 새로운 배열을 생성하여 반환합니다.  - filter()는 호출되는 배열을 변화시키지(mutate) 않습니다. - 통과하는 배열이 없다면 빈 배열을 리턴 합니다
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

//arr.filter(callback(element[, index[, array]])[, thisArg])
  • find()주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환합니다.그러한 요소가 없다면 undefined를 반환합니다.  - find는 호출의 대상이 된 배열을 변경(mutate)하지 않습니다. - 배열속에 객체가 해당될경우 객체 전체를 리턴합니다.
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
  • findIndex()주어진 판별 함수를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환합니다.만족하는 요소가 없으면 -1을 반환합니다. 
  • forEach()주어진 함수를 배열 요소 각각에 대해 실행합니다. 
arr.forEach(callback(currentvalue[, index[, array]])[, thisArg])
const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"
//////////////////////////////////////////////////////////
const items = ['item1', 'item2', 'item3'];
const copy = [];

// 이전
for (let i=0; i<items.length; i++) {
  copy.push(items[i]);
}

// 이후
items.forEach(function(item){
  copy.push(item);
});
  • includes()배열에 특정 요소가 포함돼있는지 알아내어 true 또는 false를 반환합니다.  - 인덱스를 지정하여 탐색 가능합니다
arr.includes(valueToFind[, fromIndex])
  • indexOf()배열에서 지정한 값과 같은 요소의 첫 인덱스를 반환합니다.없으면 -1을 반환합니다. 
arr.indexOf(searchElement[, fromIndex])
  • join()배열의 모든 요소를 문자열로 변환하여 합칩니다.  - 비어있는 배열을 파라미터로 받으면 빈 문자열을 반환합니다" - 원본 배열을 변환하지 않습니다
const 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"
  • keys()배열의 각 인덱스를 키 값으로 가지는 새로운 배열 반복자 객체를 반환합니다.  -원본 배열에 영향을 주지않습니다
const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();
iterator[0] = 'string'
console.log(iterator)
//Object { 0: "string" }
for (const key of iterator) {
  console.log(key);
}
// expected output: 0
// expected output: 1
// expected output: 2
  • lastIndexOf()지정된 요소가 배열에서 발견될 수 있는 마지막 인덱스를 반환하고, 존재하지 않으면 -1을 반환합니다. 
const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

console.log(animals.lastIndexOf('Dodo'));
// expected output: 3

console.log(animals.lastIndexOf('Tiger'));
// expected output: 1
  • map()배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출하고, 그 결과를 모아서 만든 새로운 배열을 반환합니다.  - 원본 배열을 변환하지 않습니다
const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]
arr.map(callback(currentValue[, index[, array]])[, thisArg])
  • pop()배열에서 마지막 요소를 제거하고 그 요소를 반환합니다.  - 빈 배열일 경우 undefined를 반환합니다 - 원본 배열의 값을 변환합니다.
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];

var popped = myFish.pop();

console.log(myFish); // ['angel', 'clown', 'mandarin' ] 

console.log(popped); // 'sturgeon'
  • push()배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환합니다.  - 원본 배열의 값을 변환합니다 - "새로운 길이"를 리턴합니다
const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('cows');
console.log(count);
// expected output: 4
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]


// 기존의 배열에 배열을 더하고 싶을경우 ( 새로운 배열을 만들고 싶지 않을떄)
var array = ['a', 'b'];
var elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]

//번외지만 기억했으면 하는것
const numbers = [5, 6, 2, 3, 7];

const max = Math.max.apply(null, numbers);
console.log(max);
// expected output: 7
const min = Math.min.apply(null, numbers);
console.log(min);
// expected output: 2
  • reduce()배열의 각 요소에 대해 주어진 함수(reducer 함수)를 적용하여 하나의 값으로 줄입니다.왼쪽에서 오른쪽 방향으로 적용합니다.  - 콜백의 최초 호출 때 accumulator와 currentValue는 다음 두 가지 값 중 하나를 가질 수 있습니다. 만약 reduce() 함수 호출에서 initialValue를 제공한 경우, accumulator는 initialValue와 같고 currentValue는 배열의 첫 번째 값과 같습니다. initialValue를 제공하지 않았다면, accumulator는 배열의 첫 번째 값과 같고 currentValue는 두 번째와 같습니다. - 객체로 이루어진 배열에 들어 있는 값을 합산하기 위해서는 반드시 초기값을 주어 각 항목이 여러분의 함수를 거치도록 해야 합니다. - mdn 속성으로 객체 분류하는거 너무 이해하기 힘듬 ㅠㅠ - 가장어려운 메소드인듯... - 원본 배열을 변경하지 않습니다.
arr.reduce(callback[, initialValue])
[0, 1, 2, 3, 4].reduce( (prev, curr) => prev + curr ); //화살표 함수

//중첩 배열 펼치기
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  function(accumulator, currentValue) {
    return accumulator.concat(currentValue);
  },
  []
);
// 펼친 결과: [0, 1, 2, 3, 4, 5]
  • reduceRight()배열의 각 요소에 대해 주어진 함수를 적용하여 하나의 값으로 줄입니다.오른쪽에서 왼쪽 방향으로 적용합니다.  - 리듀스가 왼쪽부터 적용한다면 이 메소드는 오른쪽부터 적용
  • reverse()배열의 요소 순서를 반전시킵니다.  - 소스가된 배열의 값을 변환합니다
const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]
  • shift()배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환합니다.  - 제거된 배열의 요소(value)을 반환합니다 - 소스가 된 배열의 값을 변환합니다
const array1 = [1, 2, 3];
console.log(array1);
// expected output: Array [2, 3]
  • slice()배열의 일부를 추출한 새 배열을 반환합니다.원본 배열은 수정되지 않습니다.  - 원본 배열의 값을 변환하지 않습니다
const 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"]
  • some()배열 안의 어떤 하나의 요소라도 주어진 함수를 통과하는지 테스트하고 만족한다면 true를 반환합니다.  - some은 호출한 배열을 변형하지 않습니다.
const array = [1, 2, 3, 4, 5];

// checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// expected output: true
  • sort()배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다.기본 정렬 순서는 유니코드 코드 포인트를 따릅니다.  - compare function을 정해주지 않으면 유니코드 즉 ( 십의자리더라도 1의자리기준 정렬, 문자열이면 abcd순으로 (문자열이 길더라도 첫번째 스펠링 기준으로 정렬된다) - 원본 배열의 값은 변환합니다
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);

// [1, 2, 3, 4, 5]

// 결과값이 음수가 나오면 앞에있는것이 인덱스 0쪽으로 가게된다
//+가 나오면 뒤쪽으로
// 그리고 같을경우도 정해주어야 하는데 0을 지정해주면 같은자리에 있는다
  • splice()배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경합니다.  - 제거한 요소를 담은 배열. 하나의 요소만 제거한 경우 길이가 1인 배열을 반환합니다. 아무 값도 제거하지 않았으면 빈 배열을 반환합니다. - 원본 배열의 값은 변환합니다
const 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"]

const arr2 = months.splice(4, 1, 'May');
console.log(arr2) /// 이값은 'june'가 나오게 된다
  • toLocaleString()배열의 요소를 나타내는 지역화된 문자열을 반환합니다.  - 원본 배열을 변화하지 않습니다 - 모든 요소를 문자열화 합니다 - 이 문자열은 locale 고유 문자열(가령 쉼표 “,”)에 의해 분리됩니다.
const localeString = array1.toLocaleString()
  • toString()배열과 요소를 나타내는 문자열을 반환합니다.  - 원본 배열을 변화하지 않습니다
const array1 = [1, 2, 'a', '1a'];
const array2 = array1.toString()
console.log(array2);
console.log(array1)
//> "1,2,a,1a"
//> Array [1, 2, "a", "1a"]
  • unshift()새로운 요소를 배열의 맨 앞쪽에 추가하고, 새로운 길이를 반환합니다.  - 원본 배열의 값을 변환합니다
const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5
let con = array1.unshift(4,5)
console.log(con)   /// con = 5;
console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]
  • values()배열의 각 인덱스에 대한 값을 가지는 새로운 배열 반복자 객체를 반환합니다.