오늘은 js 문제를 풀다가 막힌 부분에 대해서 공부한 것을 정리해볼 것이다.
indexOf() 메소드는 배열에서 지정된 요소를 찾을 수 있는 첫번째 인덱스를 반환하고 존재하지 않으면 -1을 반환한다.arr.indexOf(searchElement [, fromIndex])
const pasta = ['tomato', 'basil', 'onion', 'chicken'];
const pizza = ['tomato', 'cheese', 'onion', 'olive', 'beef'];
const pastaAndPizza = pasta.concat(pizza);
console.log(pastaAndPizza);
// [ 'tomato', 'basil', 'onion', 'chicken', 'tomato', 'cheese', 'onion', 'olive', 'beef' ]
pastaAndPizza.indexOf('tomato'); // 0
pastaAndPizza.indexOf('onion'); // 2
// 만약 4번째 인덱스 tomato와 6번째 onion을 찾고 싶다면?
// fromIndex 값을 써주면 된다.
pastaAndPizza.indexOf('tomato', 1); //4
pastaAndPizza.indexOf('onion', 3); // 6
filter() 메소드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환한다. 만약 조건에 부합되는 요소가 아무것도 없다면 빈 배열을 반환한다.
arr.filter(callbackFunction, thisAgr)
arr.filter(callback(element[,index[,array]]) [,thisAgr])
callbackFunction 안에서 필수적으로 받는 매개변수는 element이고, index, array는 선택적이다. 또한 thisAgr도 선택적이다.
callback은 각 요소를 시험할 함수로 true를 반환하면 요소를 유지하고, false를 반환하면 요소를 빼버린다.
처리되는 요소의 범위는 callback 함수의 첫 호출 전에 설정되고, filter() 호출 시작 이후로 배열에 추가된 요소는 callback 함수를 거치지 않는다.
배열의 기존 요소가 변경 또는 삭제된 경우, callback에 전달된 값은 filter()가 그 요소를 방문한 시점에 값이 된다. 삭제된 요소는 반영되지 않는다.
내가 처음에 풀었을 때
const pasta = ['tomato', 'basil', 'onion','chicken'];
const pizza = ['tomato', 'cheese', 'onion','olive','beef'];
function totalIngredients () {
const pastaAndPizza = pasta.concat(pizza);
pastaAndPizza.filter((el, index) => {return pastaAndPizza.indexOf(el) === index})
};
console.log(totalIngredients());
undefined가 나왔음.문제의 원인을 찾고 코드를 수정
filter()는 새로운 배열을 반환하기 때문에 배열을 반환할 변수가 필요했다.return 반환해야 됐다.const pasta = ['tomato', 'basil', 'onion', 'chicken'];
const pizza = ['tomato', 'cheese', 'onion', 'olive', 'beef'];
function totalIngredients () {
const pastaAndPizza = pasta.concat(pizza);
console.log(pastaAndPizza);
const result =
pastaAndPizza.filter((ingredient, index) => {
return pastaAndPizza.indexOf(ingredient) === index
})
return result;
};
console.log(totalIngredients());
// [ 'tomato', 'basil', 'onion', 'chicken', 'cheese', 'olive', 'beef' ]
return 하고 싶다면 바로 return pastaAndPizza.filter() 하면 된다.function totalIngredients () {
const pastaAndPizza = pasta.concat(pizza);
console.log(pastaAndPizza);
return pastaAndPizza.filter((ingredient, index) => {
return pastaAndPizza.indexOf(ingredient) === index
Set 객체는 자료형에 관계 없이 원시 값과 객체 참조 모두 유일한 값을 저장할 수 있다.
삽입 순서대로 요소를 순회할 수 있다.
Set 내의 값은 유일해야 하기 때문에 값이 같은지 검사를 수행한다.
new Set(iterable)
const fruits = ['cherry', 'grape', 'orange', 'mango', 'cherry'];
const set1 = new Set(fruits);
console.log(set);
//Set(4) {
// 'cherry',
// 'grape',
// 'orange',
// 'mango',
// __proto__: {
// constructor: ƒ Set(),
// has: ƒ has(),
// add: ƒ add(),
// delete: ƒ delete(),
// clear: ƒ clear(),
// entries: ƒ entries(),
// forEach: ƒ forEach(),
// size: 4,
// values: ƒ values(),
// keys: ƒ values()
// }
// }
// 매개변수를 명시하지 않거나 null을 전달할 경우
const set2 = new Set();
console.log(set2);
// Set(0) {
// __proto__: {..}
// }
const set3 = new Set(null);
console.log(set3);
// Set(0) {
// __proto__: {..}
// }
이 위에 배열에서 중복된 요소를 제거하는 방법을 Set을 이용해서 중복을 제거해줄 수 있다.
const pasta = ['tomato', 'basil', 'onion', 'chicken'];
const pizza = ['tomato', 'cheese', 'onion', 'olive', 'beef'];
const pastaAndPizza = pasta.concat(pizza);
const set1 = new Set(pastaAndPizza);
console.log(set1);
// 배열이 아니라 Set 객체로 나오기 때문에 배열로 바꿔줘야 된다.
// Array.from() 메소드를 이용해서 새로운 Array 객체를 만들어준다.
const pastaAndPizza1 = Array.from(set1);
console.log(pastaAndPizza1);
// [ 'tomato', 'basil', 'onion', 'chicken', 'cheese', 'olive', 'beef' ]
Array.from(arrayLike[, mapFn[, thisArg]]);
문제를 풀면서 오타에 대해서도 주의해야 되지만, 값을 return 했는지 여부도 잘 확인해야 된다는 생각이 들었다.
그리고 Set으로도 이 문제를 풀 수 있다고 해서 Set에 대해서 알아보는데, 오...어찌 찾아 보면 찾아볼수록 미궁 속에 빠져드는 것 같은 느낌이지만 차근차근 보면 언젠가는 Set에 대해서 많이 알 수 있게 되겠지.
오늘은 Set에 대해서 간략하게 써봤지만, 다음 번에는 Set에 대해서 더 깊게 공부해봐야 되겠다.