Programing/JavaScript

JavaScript 배열 앞에 값 추가, 삭제하기

lolly3 2023. 3. 8. 00:18

unshift() : 자바스크립트 배열의 맨 앞에 값을 추가 하기 

unshift() 는 배열의 앞에 배열을 추가해주고, 추가된 배열의 길이를 반환해준다.

배열의 길이는 배열이 추가 유무를 확인 할 때 사용할 수 있다.

const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// Expected output: 5
// array1.unshift(4, 5) 를 console.log 로 확인 하면
// 배열 4, 5를 앞에 추가 후에, length 를 반환하는걸 확인할 수 있다.

console.log(array1);
// Expected output: Array [4, 5, 1, 2, 3]
// array1 를 출력시에는 추가된 array 를 반환

 

 

shift() : 자바스크립트 배열의 맨 앞에 값을 삭제 하기 

shift() 는 배열의 첫 번째 요소를 제거하고, 제거된 요소를 반환해준다.

const array1 = [0, 1, 2, 3, 4, 5];

const firstElement = array1.shift();

console.log(array1);
// Expected output: Array [1, 2, 3, 4, 5]
// 첫 번째 요소인 0을 삭제

console.log(firstElement);
// Expected output: 0
// 삭제한 요소 0을 반환

 

사용 예제

몇일 전 SELECT BOX 의 OPTION LIST 를 만들어야 되는 일이 있었는데, 시안에서의 첫 번째 요소가 최소 였다.

조회한 API 에서 받아온 데이터에서는 최소값은 없는 상황, 이때 unshift() 를 통해 제일 앞에 최소가 들어간 요소를 추가해서 사용했다.

 

// API 에서 내려온 값
const array1 = [
  {name: '0', value: 0},
  {name: '1', value: 1},
  {name: '2', value: 2},
  {name: '3', value: 3},
  {name: '4', value: 4},
  {name: '5', value: 5}
];

// 최소값 추가
array1.unshift({name: '최소', value: -1});

console.log(array1);
// Expected output: 
// Array [
// Object { name: "최소", value: -1 }, 
// Object { name: "0", value: 0 }, 
// Object { name: "1", value: 1 },
// Object { name: "2", value: 2 },
// Object { name: "3", value: 3 },
// Object { name: "4", value: 4 },
// Object { name: "5", value: 5 }
// ]

간단하게 제일 앞에 값과