[ js ] 배열 내장 함수

전상욱·2021년 5월 21일
0

js & ts 

목록 보기
7/12

배열 내장 함수 정리해 보기.

forEach

const array = [1, 5, 7, 8, 9];

function print(x) {
  console.log(x);
}

array.forEach(print);

화살표 함수로 더 간단하게

const array = [1, 5, 7, 8, 9];

array.forEach(x => console.log(x))

map

기존 배열에 특정 조건을 달아서 새로운 배열을 만들때 쉽게 해주는 함수

기존 array 라는 배열에 x2 를 하는 경우.


const array = [1, 5, 7, 8, 9];

const cal = n => n * 2 
const result = array.map(cal)
console.log(result)

// 더 간단하게도 가능
const result = array.map( n => n * 2)
console.log(result)

객체로 이루어진 배열에서 뭔가를 얻을때

const ex = [
  {
    id: 1,
    text: "content1",
    done: true
  },

  { 
    id: 2, 
    text: "content2", 
    done: true },

  {
    id: 3,
    text: "content3",
    done: true
  },

  {
    id: 4,
    text: "content4",
    done: false
  }
];

const texts = ex.map(ex => ex.text)
console.log(texts)

indexOf

내가 찾고 싶은게 어디 인덱스에 위치해 있는지 알 수 있다.

const ex = ['korea','japan','uk']
const findex = ex.indexOf('uk');
console.log(findex)

findIndex

indexOf는 특정값을 알 고 있을때, 그 값을 넣어서 그 값의 대한 인덱스를 알 수 있기는 편하나
내가 값을 모르거나, 객체이거나 복잡한 경우에 쓰기에는 find가 더 편하다.
즉, 특정 조건으로 찾고 싶을때 사용하면 좋다.

const ex = [
  {
    id: 1,
    text: "content1",
    done: true
  },

  { 
    id: 2, 
    text: "content2", 
    done: true },

  {
    id: 3,
    text: "content3",
    done: true
  },

  {
    id: 4,
    text: "content4",
    done: false
  }
];

const findId = todos.findIndex(todo => todo.id === 3);
console.log(findId);

find

const todos = [
  {
    id: 1,
    text: "content1",
    done: true,
  },

  {
    id: 2,
    text: "content2",
    done: true,
  },

  {
    id: 3,
    text: "content3",
    done: true,
  },

  {
    id: 4,
    text: "content4",
    done: false,
  }
];

// done 이 false 를 찾으시오
const something = todos.find( something => something.done === false)
console.log(something)

filter

특정 조건을 갖고, 그것을 새롭게 배열을 만듬

//todo에 있는 done 중에서 true 를 찾아 배열로 만들어줘!
const todos = [
  {
    id: 1,
    text: "content1",
    done: true,
  },

  {
    id: 2,
    text: "content2",
    done: true,
  },

  {
    id: 3,
    text: "content3",
    done: true,
  },

  {
    id: 4,
    text: "content4",
    done: false,
  }
];

const doneTrue = todos.filter(find => find.done === true)
console.log(doneTrue)

splice

배열.splice(위치, 추출개수, 요소1, 요소2.. )

const array = [30, 40, 50]

// splice(index, 갯수)
// 즉 index 부터 몇개를 지우겠다.
array.splice(0,2)
console.log(array) // [50]
const array = ['딸기','사과']
array.splice(1,0,'바나나')
cosole.log(array) //["딸기", "바나나", "사과"]

const array = ['딸기','사과']
array.splice(1,1,'수박','바나나')
console.log(array) //["딸기", "수박", "바나나"]

slice

splice와 이름이 비슷하지만 전혀 다르다
우선 기본의 배열을 건들지 않는다. 넣는 파라미터도 다르다.

const array = [30, 40, 50]
// slice(처음, 나중) 
// 처음 index 부터 나중 -1 까지 자름, 기존 배열은 건들지 않음
const slice = array.slice(0,2)
console.log(slice)
console.log(array)

shift (unshift 배열 앞 부터 추가)

const array = [30, 40, 50]

//배열의 첫번째값을 지운다.
const shift = array.shift()
console.log(shift) // 30
console.log(array) // [40, 50]

pop (push 배열 뒤 부터 추가)

shift 의 반대라고 생각하면 됩니다.

const array = [30, 40, 50]

const pop = array.pop() // 뒤에를 뺀다.
console.log(pop) // [50]
console.log(pop) // [30,40]

concat

2개의 배열을 합쳐 주는것이다. 기존의 배열을 건들지 않는다.새로운 배열을 만든다.

const array = [30, 40, 50]
const array2 = [1, 2, 3]

const result = array.concat(array2) // 첫번째 함수. concat(두번째 함수)
console.log(result)

join

파라미터 조건을 갖고, 배열에 있는 값들을 끄집어 냅니다.

const array = [30, 40, 50]

const result = array.join(' ')
console.log(result)

reduce

const array = [30, 40, 50];

// 우선 accumulator 는 누적값, 0 은 초기값 
const result = array.reduce((accumulator, current) => accumulator + current , 0)
console.log(result) //120

//index 는 배열의 index 값 / array 는 기존 array를 말한다.

const example = [30, 40, 50];

const result = example.reduce((accumulator, current, index, array) => {
  if(index === array.length - 1) {
    return (accumulator + current) / array.length
  }
  return accumulator + current
},0)
console.log(result) 
// example 원소의 갯수를 reduce로 구함
const exmple = ['a','a','a','a','a','b','c','d']

const result = exmple.reduce((acc,current) => {
  if(acc[current]) {
    acc[current] += 1
  }
  else {
    acc[current] =1
  }
  return acc
}, {})

console.log(result)

profile
someone's opinion of you does not have to become your reality

0개의 댓글