Yuan's Blog
EN

Array

What are the array (Array) iteration methods in JavaScript?

(for loop, for…in, for…of, forEach, map, filter, every, some)

  1. The for loop allows the use of break / continue / return and gives you manual control over the index.
let arr=[0,1,2,3,4,5];
for(let i=0;i<arr.length;i++) {
  if(i>2) break;
  console.log(arr[i]);
}
// 0
// 1
// 2
  • The function of continue: skip the current iteration and move on to the next one; it does not end the entire loop.
  • The function of break: terminate the entire loop; none of the remaining iterations will run.
  • The function of return: terminate the entire function and return a value to the caller.
  1. for…of cannot iterate over plain objects (Object); it directly retrieves values.
const arr = ["apple","orange","banana"];
for (const item of arr) {
  if(item==="orange") continue;
  console.log(item);
}
  1. for…in iterates over keys. In an array, the keys are the indexes. In most cases, for…in is used to iterate over objects, and it is not recommended for iterating over arrays.
const arr=["apple","orange","banana"]
for (const item in arr){
  const.log(item);
}
// 0
// 1
// 2
  1. forEach: cannot use break / continue, and return has no effect. It does not return a new array.
const fruits = ["apple","orange","banana"];
fruits.forEach((item,index) => {
  console.log(index,item);
})
//0 apple
//1 orange
//2 banana
  1. map: executes the provided function on each element and returns a new array.
const arr = [1,2,3,4];
const newArr = arr.map((x) => x + 1);
console.log(newArr);
// [2,3,4,5]
console.log(arr);
// [1,2,3,4] // The original array is not modified
  1. filter: creates and returns a new array by removing any elements that do not pass the provided function.
const arr = [19,2,13,40];
const newArr = arr.filter((x) => x > 18);
console.log(newArr);
// [19, 40]
console.log(arr);
// [19, 2, 13, 40] // The original array is not modified
//
  1. every: returns a boolean value. If all elements satisfy the condition → true. If any one fails → it returns false early.
[12,5,8,130,44].every((x) => x>10); //false
[12,54,18,130,44].every((x) => x>10); //false
  1. some: as long as at least one element in the array passes the test function, it returns true.
[2,5,8,1,4].some((x)=> x>10);//false
[12,5,8,1,4].some((x) => x>10);//false
  • map and filter return new arrays. Because of this, they are frequently used in environments like React where immutable code is required.

In JavaScript, if you pass (a, b) => b - a to sort, is it ascending or descending? Why?

  • Key mechanism (the part you really need to understand): Array.prototype.sort(compareFn) relies on the three possible return values of compareFn:

    • 0 → a is placed after b

    • < 0 → a is placed before b
    • = 0 → positions stay the same
  • Therefore: a - b → smaller values come first → ascending b - a → larger values come first → descending

How do you calculate the average of an array in JavaScript?

  1. Solution using a for loop
function getAverage(array){
  let sum =0;
  for(let i=0;i<array.length;i++){
    sum += array[i]
  }
  return sum/array.length
}
  1. Functional programming solution using reduce
const getAverage = (array) =>
  array.reduce((sum,currentValue) => sum+currentValue,0)/array.length

请实践数组扁平化 (flatten)

  1. flat()
let array = [1, 2, [3, [4, 5, [6, 7, [8]]]]];

function flatten (arr) {
  return arr.flat(Infinity);
}

const flattenArray = flatten(array);
console.log(flattenArray); //[1,2,3,4,5,6,7,8]
  1. reduce
let array = [1, 2, [3, [4, 5, [6, 7, [8]]]]];
function flatten (arr) {
  return arr.reduce((acc,cur) =>
    Array.isArray(arr) ? [...acc,...flatten(cur)]:[...acc,cur]
    ,[])
}
const flattenArray = flatten(arrty);
console.log(flattenArray);//[1,2,3,4,5,6,7,8]
  • …flatten(cur): destructures the flattened result. The ... is the spread operator, which expands each element of an iterable (such as an array) into individual values. For example:
[... [1,2,3]]
  [1,2,3]

Methods for Removing Duplicates from an Array

  1. Solution 1: Use Set to remove duplicates. A Set can only store unique values of any data type.
function removeDuplicate(arr){
  return [...new Set(arr)];
}
  1. Using filter together with indexOf
function removeDuplicate(arr) {
  return arr.filter((item,index,array) => array.indexOf(item) === index);
}