๐Ÿ“š Array methods in JavaScript

ยท

2 min read

๐Ÿ“š Introduction:

Arrays are one of the most commonly used data structures in JavaScript. They are used to store and manipulate collections of data.

While coding in JavaScript, it is most likely that you will fall under circumstances where you have to manipulate an array.

JavaScript has a variety of built-in array methods that make it easier to work with arrays. In this blog post, we will explore some of the modern array methods in JavaScript and provide examples using emojis to make it fun and easy to understand.

๐Ÿ” forEach():

The forEach() method executes a provided function once for each array element.

const emojis = ["๐Ÿ˜€", "๐Ÿ˜†", "๐Ÿ˜Š", "๐Ÿ˜"];

emojis.forEach((emoji) => {
  console.log(emoji);
});

// Output:
// ๐Ÿ˜€
// ๐Ÿ˜†
// ๐Ÿ˜Š
// ๐Ÿ˜

๐Ÿ” map():

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

const numbers = [1, 2, 3, 4, 5];

const doubledNumbers = numbers.map((number) => {
  return number * 2;
});

console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

๐Ÿ” filter():

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

const numbers = [1, 2, 3, 4, 5];

const evenNumbers = numbers.filter((number) => {
  return number % 2 === 0;
});

console.log(evenNumbers); // Output: [2, 4]

๐Ÿ” find():

The find() method returns the value of the first element in the array that satisfies the provided testing function.

const emojis = ["๐Ÿ˜€", "๐Ÿ˜†", "๐Ÿ˜Š", "๐Ÿ˜"];

const happyEmoji = emojis.find((emoji) => {
  return emoji === "๐Ÿ˜€" || emoji === "๐Ÿ˜Š";
});

console.log(happyEmoji); // Output: "๐Ÿ˜€"

๐Ÿ” reduce():

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

const numbers = [1, 2, 3, 4, 5];

const sumOfNumbers = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

console.log(sumOfNumbers); // Output: 15

๐Ÿ” some():

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

const numbers = [1, 2, 3, 4, 5];

const hasEvenNumber = numbers.some((number) => {
  return number % 2 === 0;
});

console.log(hasEvenNumber); // Output: true

๐Ÿ” every():

The every() method tests whether all elements in the array pass the test implemented by the provided function.

const numbers = [2, 4, 6, 8, 10];

const allEvenNumbers = numbers.every((number) => {
  return number % 2 === 0;
});

console.log(allEvenNumbers); // Output: true