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]
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 컬렉션에 존재합니다.