자바스크립트-배열

BackEnd_Ash.log·2020년 3월 28일
0

자바스크립트

목록 보기
5/29

https://learnjs.vlpt.us/basics/09-array-functions.html

forEach

forEach() 메소드는 주어진 함수를 배열요소 각각에 대해 실행합니다.

const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];

for ( let i =0 ; i < superheroes.length; i++) {
	console.log(superheroes[i]);
}

이렇게 for 반복문을 사용하면 되지만 ,
조금더 간단하게 ,


const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];

superheroes.forEach(hero => {
	console.log(hero);
});

이렇게 출력 할 수 있다 .

map

map 은 배열 내의 모든 요소 각각에 대하여 주어진 함수를 적용한 결과를 모아
새로운 배열을 반환합니다.


const array = [1,2,3,4,5,6,7,8];

const squared = [];

for ( let i =0; i < array.length; i++) {
	squared.push(array[i] * array[i]);
}

console.log(squared);

이렇게 할 수 있는데 forEach 를 사용하게 된다면 ??

const array = [ 1, 2, 3, 4, 5, 6, 7 ,8];

const squared = [];

array.forEach(n => {
	squared.push(n*n);
}); 

console.log(squared); //[1, 4, 9, 16, 25, 36, 49, 64];

이렇게 사용도 가능하다. map 을사용하면 ?


const array = [ 1, 2, 3, 4, 5, 6, 7 ,8];

const square = n => n * n ;
const squared = array.map(square);
console.log(squared);//[1, 4, 9, 16, 25, 36, 49, 64];
const array = [ 1, 2, 3, 4, 5, 6, 7 ,8];

const squared = array.map(n => n * n );
console.log(squared);//[1, 4, 9, 16, 25, 36, 49, 64];
const items = [
  {
    id : 1 ,
    text : 'hello'
  },
  {
    id:2,
    text : 'bye'
  }
];

const texts = items.map(item => item.text);
console.log(texts); 
//["hello", "bye"]
//0: "hello"
//1: "bye"

indexOf

해당하는 아이템이 index 어디에 있는지 찾아주는 함수입니다.

const superheroes = ['아이언맨','캡틴 아메리카','토르','닥터 스트렌지'];
const index = superheroes.indexOf('토르');
console.log(index); // 2 

2 가 출력됩니다.

findIndex

const todos=[
  {
    id:1,
    text:'asdfasdf',
    done : true,
  },
  {
    id:2,
    text:'zxcvasdf',
    done:true,
  },
  {
    id:3,
    text:'asdfxcv23f',
    done:true,
  },
  {
    id:4,
    text:'avdvlkwev',
    done:false
  }
]

const index = todos.findIndex(todo => todo.id ===3);
console.log(index); // 2

findIndex 는 찾고자 하는 값에 index 를 가르쳐 줍니다.
indexOf 랑 무슨차이가 있을까 ?? 생각을 했었는데 ,
findIndex 는 객체라던지 그러한 조건들이 있을때 findIndex 를 사용한다고 하네요 .

find


const todos=[
  {
    id:1,
    text:'asdfasdf',
    done : true,
  },
  {
    id:2,
    text:'zxcvasdf',
    done:true,
  },
  {
    id:3,
    text:'asdfxcv23f',
    done:true,
  },
  {
    id:4,
    text:'avdvlkwev',
    done:false
  }
]

const index = todos.find(todo => todo.id ===3);
console.log(index); // Object {id: 3, text: "asdfxcv23f", done: true}

filter

const numbers = [1,2,3,4,5];
const filtered = numbers.filter(n => n > 3);
console.log(filtered); // [4,5]

const filtered = numbers.filter(n => n!==3);
console.log(filtered); // [1,2,4,5]

const todos=[
  {
    id:1,
    text:'asdfasdf',
    done : true,
  },
  {
    id:2,
    text:'zxcvasdf',
    done:true,
  },
  {
    id:3,
    text:'asdfxcv23f',
    done:true,
  },
  {
    id:4,
    text:'avdvlkwev',
    done:false
  }
]

const tasksNotDone = todos.filter(todo => todo.done ===true);
console.log(tasksNotDone);
/*
[Object, Object, Object]
0: Object
id: 1
text: "asdfasdf"
done: true
1: Object
id: 2
text: "zxcvasdf"
done: true
2: Object
id: 3
text: "asdfxcv23f"
done: true
*/

splice

splice( index , 몇개 자를것인지) ;


const numbers = [10,20,30,40];
const index = numbers.indexOf(30);
const spliced = numbers.splice(index , 2);
console.log(spliced); // [30 , 40]
console.log(numbers); // [10 , 20]

slice

배열을 잘라주는 함수


const numbers = [10,20,30,40];
const sliced = numbers.slice(0,2);
console.log(sliced); // [10, 20]
console.log(numbers); // [10,20,30,40] 

const numbers = [1,2,3,4,5]
const sliced = numbers.slice(0,3);
console.log(sliced); // [ 1 , 2 , 3 ]

const sliced = numbers.slice(3,5);
console.log(sliced); // [ 4 ,5 ]

const sliced = numbers.slice(0,2).concat(numbers.slice(3,5))
console.log(sliced); // [1 , 2 ,4 , 5]

shift

shift 는 배열의 맨 앞에 있는 원소들을 하나씩 꺼냅니다.


const numbers = [10,20,30,40];

const value = numbers.shift();
console.log(value); // 10
console.log(numbers); // [20 ,30 ,40 ]

unshift

shift 가 앞에서부터 원소들을 하나씩 꺼낸다고 하면
unshift 는 앞에서 부터 원소들을 집어넣게 됩니다.

const numbers = [10,20,30,40];

numbers.unshift(5);
console.log(numbers);//[5, 10, 20, 30, 40]

pop


const numbers = [10,20,30,40];

const value = numbers.pop();
console.log(value); // 40
console.log(numbers) // [10 , 20 , 30]

배열에 새 항목 추가하기-push()

pop 은 뒤에서 하나씩 꺼낸다고 하면
push 뒤에서 부터 원소를 하나씩 넣는다고 생각하시면 됩니다.

const numbers = [10,20,30,40];

numbers.push(50);
console.log(numbers);//[10, 20, 30, 40, 50]

배열 이어 붙이기-concat()

두개의 배열을 합쳐주는 역할을 합니다.

const arr1 = [1,2,3];
const arr2 = [4,5,6];
const concated = arr1.concat(arr2);
console.log(concated); //[1, 2, 3, 4, 5, 6]

join

const array = [1,2,3,4,5];
console.log(array.join());//1,2,3,4,5 
console.log(array.join(' ')) //1 2 3 4 5 

reduce

const numbers = [1,2,3,4,5];

let sum =0;
numbers.forEach( n => {
	sum += n;
});

console.log(sum); //15 

이 코드를 조금더 깔끔하게 정리 할 수가 있습니다 .


const numbers = [1 , 2 , 3 , 4 , 5];

const sum = numbers.reduce((accumulator , current) => accumulator + current , 0);
console.log(sum); // 15 

똑같이 15 가 되는데 ,
일단 초기값 0 이 numbers.reduct((accumulator , ~~~ 에 있는
accumulator 가 되구요 .
current 는 처음에 1 이 들어가게 됩니다.

그래서 0 + 1 은 1 이 되구
다시 1 이 accumulator 가 됩니다.
해서 반복으로 15 라는 값이 나오게 됩니다.


const numbers = [ 1, 2, 3, 4 ,5];

const sum = numbers.reduce((accumulator , current , index , array) => {
  if (index === array.length -1 ) {
		return (accumulator + current) / array.length;    
  }
  return accumulator + current;
} , 0);
console.log(sum);

const alphabets = ['a' , 'a' , 'a' , 'b' , 'c' , 'c' , 'd' , 'e' ];
const counts 
= alphabets.reduce((acc , current) => {
	if (acc[current]) {
      acc[current] +=1;
    }else {
      acc[current] =1;
    }
  return acc;
}, {})

console.log(counts); // Object {a: 3, b: 1, c: 2, d: 1, e: 1}

Array.from

function translate() {
  return Array.from(arguments, (value) => value + 1);
}

const numbers = translate(1, 2, 3);
console.log(numbers); // [ 2, 3, 4 ]
profile
꾸준함이란 ... ?

0개의 댓글