JavaScript Array Methods: Mastering Array Manipulation Techniques with Examples
0 0
Read Time:6 Minute, 24 Second

JavaScript arrays are powerful data structures that allow you to store and manipulate a list of values. They come with extensive methods that make it easier to perform various operations, such as adding, removing, searching, and sorting elements. Understanding these methods is crucial for any developer looking to master JavaScript. In this guide, we’ll explore 34 essential JavaScript array methods, explaining each with simple examples to help you grasp their functionality.

List Of JavaScript Array Methods:

  1. pop() – Remove the Last Element
  2. shift() – Remove the First Element
  3. unshift() – Add Elements to Start
  4. concat() – Merge Arrays
  5. sort() – Sort Array Elements
  6. splice() – Add/Remove Elements
  7. slice() – Extract Array Part
  8. reverse() – Reverse Array Order
  9. isArray() – Check if the Array
  10. indexOf() – Find Element Index
  11. lastIndexOf() – Find Last Element Index
  12. find() – Find Element by Predicate
  13. findIndex() – Find the Element Index by Predicate
  14. includes() – Check if the Array Includes Element
  15. entries() – Array Iterator
  16. every() – Test All Elements
  17. some() – Test Any Element
  18. fill() – Fill the Array with Value
  19. copyWithin() – Copy Array Elements
  20. valueOf() – Get Array Primitive Value
  21. forEach() – Execute Function on Each Element
  22. map() – Transform Array Elements
  23. filter() – Filter Array Elements
  24. reduce() – Reduce to Single Value
  25. reduceRight() – Reduce Right to Left
  26. flat() – Flatten Nested Arrays
  27. flatMap() – Map and Flatten
  28. from() – Create an Array from Iterable
  29. keys() – Array Keys Iterator

1. toString()

Converts the array to a string, separating elements with commas.

const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits.toString()); // Output: "Apple,Banana,Cherry"

2. join()

Joins all elements of an array into a string, with an optional separator.

console.log(fruits.join(" - ")); // Output: "Apple - Banana - Cherry"

3. push()

Adds one or more elements to the end of an array and returns the new length.

fruits.push("Date");
console.log(fruits); // Output: ["Apple", "Banana", "Cherry", "Date"]

4. pop()

Removes the last element from an array and returns that element.

const lastFruit = fruits.pop();
console.log(lastFruit); // Output: "Date"

5. shift()

Removes the first element from an array and returns that removed element.

const firstFruit = fruits.shift();
console.log(firstFruit); // Output: "Apple"

6. unshift()

Adds one or more elements to the beginning of an array and returns the new length.

fruits.unshift("Strawberry");
console.log(fruits); // Output: ["Strawberry", "Banana", "Cherry"]

7. concat()

Merges two or more arrays without changing the existing arrays.

const moreFruits = ["Mango", "Peach"];
const allFruits = fruits.concat(moreFruits);
console.log(allFruits); // Output: ["Strawberry", "Banana", "Cherry", "Mango", "Peach"]

8. sort()

Sorts the elements of an array in place and returns the array.

const numbers = [3, 1, 4, 1, 5, 9];
numbers.sort();
console.log(numbers); // Output: [1, 1, 3, 4, 5, 9]

9. splice()

Adds/removes elements from an array and returns the removed elements.

numbers.splice(2, 0, 2); // Insert '2' at index 2
console.log(numbers); // Output: [1, 1, 2, 3, 4, 5, 9]

10. slice()

Returns a shallow copy of a portion of an array.

const numbersCopy = numbers.slice(1, 4);
console.log(numbersCopy); // Output: [1, 2, 3]

11. reverse()

Reverses the order of the elements in an array.

const reversedNumbers = numbers.reverse();
console.log(reversedNumbers); // Output: [9, 5, 4, 3, 2, 1, 1]

12. isArray()

Determines whether the passed value is an Array.

console.log(Array.isArray(numbers)); // Output: true

13. indexOf()

Returns the first index at which a given element can be found in the array.

console.log(numbers.indexOf(4)); // Output: 2

14. lastIndexOf()

Returns the last index at which a given element can be found in the array.

console.log(numbers.lastIndexOf(1)); // Output: 6

15. find()

Returns the value of the first element in the array that satisfies the provided testing function.

const found = numbers.find(element => element > 4);
console.log(found); // Output: 5

16. findIndex()

Returns the index of the first element in the array that satisfies the provided testing function.

const foundIndex = numbers.findIndex(element => element > 4);
console.log(foundIndex); // Output: 1

17. includes()

Determines whether an array includes a certain value.

console.log(numbers.includes(4)); // Output: true

18. entries()

Returns a new Array Iterator object that contains the key/value pairs for each index in the array.

const iterator = numbers.entries();
console.log(iterator.next().value); // Output: [0, 9]

19. every()

Tests whether all elements in the array pass the test implemented by the provided function.

const allEven = numbers.every(element => element % 2 === 0);
console.log(allEven); // Output: false

20. some()

Tests whether at least one element in the array passes the test implemented by the provided function.

const someEven = numbers.some(element => element % 2 === 0);
console.log(someEven); // Output: true

21. fill()

Fills all the elements of an array from a start index to an end index with a static value.

numbers.fill(0, 2, 4);
console.log(numbers); // Output: [9, 5, 0, 0, 1, 1]

22. copyWithin()

Copies a sequence of array elements within the array.

numbers.copyWithin(1, 3, 5);
console.log(numbers); // Output: [9, 0, 0, 0, 1, 1]

24. valueOf()

Returns the primitive value of the specified object.

console.log(numbers.valueOf()); // Output: [9, 0, 0, 0, 1, 1]

25. forEach()

Executes a provided function once for each array element.

numbers.forEach((value, index) => {
 console.log(`Index ${index}: ${value}`);
});

26. map()

Creates a new array populated with the results of calling a provided function on every element in the calling array.

const squaredNumbers = numbers.map(x => x * x);
console.log(squaredNumbers); // Output: [81, 0, 0, 0, 1, 1]

27. filter()

Creates a new array with all elements that pass the test implemented by the provided function.

const filteredNumbers = numbers.filter(x => x > 0);
console.log(filteredNumbers); // Output: [9, 1, 1]

28. reduce()

Executes a reducer function on each element of the array, resulting in a single output value.

const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(sum); // Output: 11

29. reduceRight()

Applies a function against an accumulator and each array value (from right to left) to reduce it to a single value.

const sumRight = numbers.reduceRight((accumulator, currentValue) => accumulator + currentValue);
console.log(sumRight); // Output: 11

30. flat()

Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

const nestedNumbers = [1, [2, 3], [4, [5, 6]]];
const flatNumbers = nestedNumbers.flat(2);
console.log(flatNumbers); // Output: [1, 2, 3, 4, 5, 6]

31. flatMap()

First, it maps each element using a mapping function, then flattens the result into a new array.

const flatMappedNumbers = nestedNumbers.flatMap(x => x);
console.log(flatMappedNumbers); // Output: [1, 2, 3, 4, [5, 6]]

32. from()

Creates a new, shallow-copied Array instance from an array-like or iterable object.

const arrayFromString = Array.from("12345");
console.log(arrayFromString); // Output: ["1", "2", "3", "4", "5"]

33. keys()

Returns a new Array Iterator object that contains the keys for each index in the array.

const keysIterator = numbers.keys();
for (const key of keysIterator) {
  console.log(key);
}

Conclusion

In this guide, we’ve covered the essentials of JavaScript array methods, providing a solid foundation for you to explore and experiment with these powerful tools. Remember, practice is key to mastering JavaScript, so try out these examples and see how you can apply them to your projects.

♥️ If you find it useful, please express your appreciation by giving it a like! (P.S. -It won’t cost anything don’t worry just go for it 😉)

✍️ Feel free to comment with your thoughts and queries (Trust me it motivates me a lot 💎)

📥 Don’t forget to Bookmark it for later use (Or else you’ll miss it 🥲)

📲 Also share it with your friends and colleagues out there (Let’s help each other grow 👊🏻)

Do Follow Us on:

Facebook.com

Twitter.com

Also Read: Top 5 Emerging AI Trends To Watch Out In 2023

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

By Akash Kothari

I am passionate about my work. Because I love what I do, I have a steady source of motivation that drives me to do my best. In my last job, this passion led me to challenge myself daily and learn new skills that helped me to do better work

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

One thought on “JavaScript Array Methods: Mastering Array Manipulation Techniques with Examples

  1. What i dont understood is in reality how youre now not really a lot more smartlyfavored than you might be now Youre very intelligent You understand therefore significantly in terms of this topic produced me personally believe it from a lot of numerous angles Its like women and men are not interested except it is one thing to accomplish with Woman gaga Your own stuffs outstanding Always care for it up

Leave a Reply

Discover more from TechDevil

Subscribe now to keep reading and get access to the full archive.

Continue reading