filter(), indexOf()

suyeon·2022년 1월 18일
0

1. filter( ) : 배열에서 특정 값 개수 구하기

const array = ['a', 'b', 'c', 'a'];

// array에서 'a' 개수 구하기
let count 
  = array.filter(element => 'a' === element).length;

2. indexOf( )

  • 배열의 모든 요소 찾기
var indices = [];
var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var element = 'a';
var idx = array.indexOf(element);
while (idx != -1) {
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// [0, 2, 4]
  • 배열에서 다른 수 찾는 방법 : forEach(), indexOf()
const array = [];

input.forEach(x => {
     const num = x % 42;
    
    if (array.indexOf(num) === -1) { // array에서 num이 발견되지 않는 경우 -1을 반환
        array.push(num);
    }
});
  • 요소가 배열에 존재하는지 확인하고 배열을 업데이트
function updateVegetablesCollection (veggies, veggie) {
    if (veggies.indexOf(veggie) === -1) {
        veggies.push(veggie);
        console.log('새로운 veggies 컬렉션 : ' + veggies);
    } else if (veggies.indexOf(veggie) > -1) {
        console.log(veggie + ' 은 이미 veggies 컬렉션에 존재합니다.');
    }
}

var veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];

updateVegetablesCollection(veggies, 'spinach');
// 새로운 veggies 컬렉션 : potato, tomato, chillies, green-pepper, spinach
updateVegetablesCollection(veggies, 'spinach');
// spinach 은 이미 veggies 컬렉션에 존재합니다.

0개의 댓글