Sobes.tech
Junior

What methods are you familiar with for iterating over arrays?

sobes.tech AI

Answer from AI

  • for
  • for...of
  • forEach()
  • map()
  • filter()
  • reduce()
  • some()
  • every()
  • find()
  • findIndex()

Each of these methods has its own features and is suitable for different tasks. For example, forEach simply iterates over elements without creating a new array. map and filter create new arrays based on the original, while reduce reduces the array to a single value. some and every check whether at least one or all elements of the array meet a condition, respectively. find and findIndex search for an element by condition or its index.

const arr = [1, 2, 3];

// for
for (let i = 0; i < arr.length; i++) {
  // Do something with arr[i]
}

// for...of
for (const element of arr) {
  // Do something with element
}

// forEach
arr.forEach(element => {
  // Do something with element
});

// map
const newArrMap = arr.map(element => element * 2);

// filter
const newArrFilter = arr.filter(element => element > 1);

// reduce
const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

// some
const hasTwo = arr.some(element => element === 2);

// every
const allGreaterThanZero = arr.every(element => element > 0);

// find
const foundElement = arr.find(element => element === 2);

// findIndex
const foundIndex = arr.findIndex(element => element === 2);