자바스크립트 filter, reduce 특정 인덱스 건너뛰기

이석원·2022년 7월 28일
0

map 과 같다.

예제)

arr = [0,1,2,3,4,9,16,17,28,89];
const test2 = arr.filter((element, index)=>{if(element === index)return; else return element>5 });
console.log(test2);

결과값 : [9, 16, 17, 28, 89]

예제)

arr = [0,1,2,3,4,9,16,17,28,89];
const except = [0,1,2,3,4]
const test2 = arr.filter((element, index)=>{
    if(except.includes(index))return;
    else return element>0
});
console.log(test2);

결과값 : [9, 16, 17, 28, 89]

reduce 도 비슷하다. return accumulator 를 할 경우 특정 인덱스를 뛰어넘을 수 있다.
예제)

const arr = ["this", {lll:1010}, "that", {aaa:2929}, "thth", {iii:2929}];
const a = (arr.reduce((acc,cur,inx,src)=>{
    if(typeof(cur) === "string") acc[cur]=src[inx+1];
    return acc;
},{}))
console.log(a)
profile
개발자 공부중

0개의 댓글