배열

배열 분석 에서 JavaScript

14개의 연습 문제

배열 분석 소개

JavaScript에서 Array의 인스턴스는 그냥 일반 객체예요. 다만 배열을 순회하고 분석하고 변경하는 데 쓸 수 있는 유용한 메서드가 많이 붙어 있죠. length 속성도 있고요. 배열의 각 원소는 그 배열의 인덱스 속성이에요. 이런 인덱스 속성을 직접 반복해서 순회하는 대신, 배열 분석을 사용해요. 배열의 내용을 분석하는 내장 함수 중 상당수는 true나 false를 반환하는 함수를 인자로 받아요. 이런 함수를 predicate라고 불러요.

일반적으로 추상화된 내장 메서드를 사용하는 편이 for나 .forEach를 쓰는 것보다 더 관용적이고 읽기 쉽고 유지보수하기 좋아요.

const values = [1, 2, 5, 8, 8, 10];

// Array#some stops iteration as soon as the given predicate returns true; it
// returns false if none of the elements in the array pass the predicate. In
// other words: return true if for some item the given function returns true.
//
const isOdd = (item) => item % 2 === 1;
const areSomeOdd = values.some(isOdd);
// => true

// Array#every stops iteration as soon as the given predicate returns false; it
// returns true if each and every element passes the predicate. In other words:
// return true if for every item the given function returns true
//
const areAllPositive = values.every((item) => item >= 0);
// => true

// Most array analysis predicates get more than one argument as their input. In
// most cases it will be:
//
// 1. item:  the current element being evaluated
// 2. index: the index associated with that element
// 3. self:  the array itself
//
// Since Array#indexOf(value) returns the first index of value in the array, it
// can be used to determine if a particular (item, index) pair does NOT match
// the first occurrence of the item. Only for the first occurrence, the index
// of the item will match the passed in index.
//
//   ['a', 'b', 'a'].indexOf('a')
//   // => 0
//
//   isDuplicate('a', 0, ['a', 'b', 'a'])
//   // => false
//   isDuplicate('b', 1, ['a', 'b', 'a'])
//   // => false
//   isDuplicate('a', 2, ['a', 'b', 'a'])
//   // => true
//
function isDuplicate(item, index, self) {
  return self.indexOf(item) !== index;
}

const indexOfFirstDuplicate = values.findIndex(isDuplicate);
// => 4

// Some of the analysis functions don't take a predicate but instead take a
// value directly.
//
// Array#includes is the same as the more verbose options:
//
//   values.some((item) => item === 42)
//   values.indexOf(42) !== -1
//
// Array#indexOf is the same as the more verbose option:
//
//   values.findIndex((item) => item === 42) !== 1
//
const hasValue42 = values.includes(42);
// => false
GitHub에서 편집 링크가 새 창이나 탭에서 열려요

배열 분석 배우기