ES5+(배열 / 배열API)

JIY00N·2023년 4월 1일
0

HTML / CSS / JavaScript

목록 보기
15/18
post-thumbnail

2023.04.01

1. 배열

  1. 선언
const arr1 = new Array();
const arr2 = [1,2];
  1. looping over an array
const fruits=["apple","banana"];
// for
for(let i = 0; i < fruits.length; i++){
  console.log(fruits[i]); // apple, banana
}
// for of
for(let fruit of fruits){
  console.log(fruit); // apple, banana
}
// forEach
fruits.forEach(function(fruit, index){
  console.log(fruit, index); // apple 0, banana 1 
})
fruits.forEach((fruit, index) => console.log(fruit, index)); // apple 0, banana 1 
  1. Addition, deletion, copy
// push: add an item to the end
// pop: remove an item from the end
fruits.push("cherry", "mango");
console.log(fruits); // apple, banana, cherry, mango
fruits.pop();
console.log(fruits); // apple, banana, cherry
// unshift: add an item to the beginning
// shift: remove an item from the beginning
fruits.unshift("mango"); 
console.log(fruits); // mango apple, banana, cherry
fruits.shift("mango"); 
console.log(fruits); // apple, banana, cherry

✔ unshift and shift are slower than push and pop!!

// splice: remove an item by index position 특정위치 삭제
fruits.push("mango","peach");
console.log(fruits); // apple, banana, cherry, mango, peach
fruits.splice(1); // 인덱스 1부터 모두 삭제
console.log(fruits); // apple
fruits.splice(1,1); // 인덱스 1부터 1개 삭제
console.log(fruits); // apple, cherry, mango, peach
fruits.splice(1,1,"melon","lemon"); // 인덱스 1부터 1개 삭제후 melon과 lemon 추가
console.log(fruits); // apple, melon, lemon, mango, peach
// combine two arrays
const fruits2 = ["peer", "watermelon"];
const newFruits = fruits.concat(fruits2);
console.log(newFruits); // apple, melon, lemon, mango, peach, peer, watermelon
  1. Searching
// indexOf - find the index
console.log(fruits); // apple, melon, lemon, mango, peach
console.log(fruits.indexOf("apple")); // 0
console.log(fruits.indexOf("mango")); // 3
console.log(fruits.indexOf("kiwii")); // -1
// includes - 배열에 찾고자하는것이 있는지 없는지
console.log(fruits.includes("melon")); // true
console.log(fruits.includes("kiwii")); // false
// lastIndexOf
console.log(fruits); // apple, melon, lemon, mango, peach
fruits.push("apple"); 
console.log(fruits); // apple, melon, lemon, mango, peach, apple
console.log(fruits.indexOf("apple")); // 0 젤 처음 등장한 것
console.log(fruits.lastIndexOf("apple")); // 5 젤 마지막에 등장한 것

2. 배열 API

  1. 배열 초기화
const arr = new Array(n+1).fill(true);
// 배열의 크기가 n+1이고, true로 채움
  1. join - 배열을 문자열로
const fruits = ['apple','banana','orange'];
const result = fruits.join();
console.log(result); // apple, banana, orange
  1. split - 문자열을 배열로
const fruits = 'apple, banana, orange, mango';
const result = fruits.split(',');
console.log(result); // ['apple', 'banana', 'orange', 'mango']
const result = fruits.split(',',2);
console.log(result); // ['apple', 'banana']
  1. reverse - 배열을 거꾸로, 원본 훼손
const array = [1,2,3,4,5];
const result = array.reverse();
console.log(result); // [5,4,3,2,1]
console.log(array); // [5,4,3,2,1] 
  1. splice - 자른 값 반환, 원본 훼손
const array = [1,2,3,4,5];
const result = array.splice(0,2);
console.log(result); // [1,2]
console.log(array); // [3,4,5] 
  1. slice - 배열의 특정 부분을 리턴, 원본 훼손 x
// slice(시작인덱스, 갯수)
const array = [1,2,3,4,5];
const result = array.slice(2,5);
console.log(result); // [3,4,5]
console.log(array); // [1,2,3,4,5]
class Student{
  constructor(name, age, enrolled, score){
  	this.name = name;
    this.age = age;
    this.enrolled = enrolled;
    this.score = score;
  }
}
const students = [
  new Student('A', 29, true, 45),
  new Student('B', 28, false, 80),
  new Student('C', 30, true, 90),
  new Student('D', 40, false,66),
  new Student('E', 18, true, 88),
];
  1. find - 콜백함수를 만들어서 전달, 첫번째로 찾아진 요소 리턴 true / undefined
// find a student with the scroe 90
const result = students.find((student)=>student.score === 90);
console.log(result); // // Student {name: "C", age:30, enrolled: true, score:90}
  1. filter - 콜백함수를 전달해서 true인것들만 모아서 배열로 전달
// make an array of enrolled students
const result = students.filter((student)=>student.enrolled);
console.log(result); // [Student, Student, Student]
  1. map - 콜백함수 전달, 배열안의 요소들을 다른것들로 변환
// make an array containing only the studnets' scores result
// shuld be: [45, 80, 90, 66, 88]
const result = students.map((sutdent) => student.score);
console.log(result); // [45, 80, 90, 66, 88]
  1. some - 콜백함수 전달, 배열의 요소중에 하나라도 콜백함수의 return이 true가 되는것이 있는지 없는지 확인
// check if there is a student with the score lower than 50
const result = students.some((student)=>student.score<50);
console.log(result); // true
  1. every - 콜백함수 전달, 배열의 모든 요소가 콜백함수의 return이 true가 되는것이 있는지 없는지 확인
// check if there is a student with the score lower than 50
const result2 = students.every((student)=>student.score<50);
console.log(result2); // false
  1. reduce - 콜백함수나 initialvalue를 전달 콜백함수는 배열안에 들어있는 모든 요소들마다 호출됨, 누적된 결과 값을 리턴, 배열안의 요소들의 합
    우리가 원하는 시작점 부터 모든 배열을 돌면서 어떤 값을 누적할 때 사용
// curr: 배열 하나하나씩 순차적으로 전달 받음
// prev: return 값을 받음
const result = students.reduce((prev, curr)=> prev+ curr.score,0); 
//  0 45 125 215 281
// ,0: 0 부터 시작
consle.log(result); // 369
consle.log(result / students.length;); // 73.8
  1. 응용 map, filter, join
//make a string containing all the scores
const result =students
.map((student)=>student.score)
.filter(score=>score>=50)
.join();
console.log(result); // 80,90,66,88
  1. sort
sort((a,b)=>a-b) //오름차순
sort((a,b)=>b-a) //내림차순
const result = students.map((student)=>student.score).sort((a,b)=>a-b).join();
console.log(result); // 45,66,80,88,90
  1. at - 배열에서 해당 값에 해당하는 인덱스의 요소를 반환
    양수와 음수 모두 지정 가능(음수일 경우 뒤에서부터 인덱스를 셈)
    구문: at(index)
const array1 = [5, 12, 8, 130, 44];
let index = 2;
console.log(array1.at(index)); // 8
console.log(array1.at(-1)); // 44
  1. 두 배열 비교하여 같은 값 찾기 filter, includes
const arr1 = [1,4,3,2];
const arr2 = [5,2,6,7,1];
const answer = arr1.filter((num)=>arr2.includes(num)); //[1,2]
  1. 숫자 문자열 배열을 숫자 배열로 바꾸기
const str = ["1", "2", "3"];
const num = str.map(Number); // [1,2,3]
  1. 2차원 배열 행,열 바꾸기
// 1. reduce와 map 활용
const transpose = matrix => matrix.reduce(
  (result, row) => row.map((_,i)=>[...(result[i]||[]),row(i)), []);
// 2. 구조분해 단, 배열의 값을 직접바꿈, n*n
function transpose(matrix) {
  for (let i = 0; i < matrix.length; i++) {
    for (let j = 0; j < i; j++) {
      [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
    }
  }
}
// 3. Array.from
// 만들고자 하는 행의 개수를 r, 열의 개수를 c
Array.from({ length: r }, () => new Array(c).fill(0))
profile
블로그 이전 했습니다. https://yoon-log.vercel.app/

0개의 댓글