Most used and Important Array Method's in JavaScript

·

6 min read

image.png

What is JavaScript? Is JavaScript is same like Java?

JavaScript is a scripting or programming language that allows you to implement complex features on web pages and it enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else. It is the third layer of the layer cake of standard web technologies after HTML and CSS.

JavaScript is an object-based scripting language and event-based approach , where Java is an object-oriented programming language and thread-based approach.

What is array in JavaScript?

In JavaScript, an array is a data structure that contains list of elements which store multiple values in a single variable. Array methods are functions built-in to JavaScript that we can apply to our arrays, Each method has a unique function that performs manipulation with respect to or calculation to our array and saves us from writing common functions from scratch.

1.map( )

This method creates a new array with the results of calling a provided function on every element in this array. In more technical manner we can say Map objects are collections of key-value pairs. A key in the Map may only occur once, it is unique in the Map's collection in case of 2 elements.

const array1 = [1, 4, 9, 16]; // pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1); // 2,8.18,32
const fullNames = students.map((element, index) => {
  return {'fullName': element['f_name'] + ' ' + element['l_name']}
});
console.log(fullNames); //added 1st name and last name
map((element) => { todo })
map((element, index) => { todo })
map((element, index, array) => { todo })

In above example we are taking only the one element for mapping if we want to take multple values the syntax follows like this

2. filter( )

This method creates a new array with only elements that passes the condition inside the provided function. In technical manner we can say like, The filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

what is shallow copy?

A shallow copy means that certain sub-values are still connected to the original variable. A new object is created that has an exact copy of the values in the original object.

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];                           
const result = words.filter(word => word.length > 6);                                                                
console.log(result); //["exuberant", "destruction", "present"]

3. sort( )

This method is used to sort array’s elements either in ascending or descending order.

arr=[5,6,3,2,1,4];
asc = arr.sort((a,b) => a > b ? 1 : -1);
console.log(asc); //1,2,3,4,5,6;
desc = arr.sort((a,b) => a > b ? -1 : 1);
console.log(desc);  // 6,5,4,3,2,1;

4. forEach( )

This method helps to loop over array by executing a provided callback function for each element in an array.

arr = [1,2,3,4];                               
arr.forEach(elemt => {
console.log(elemt
});  // 1 2 3 4

5. concat( )

This method is used to merge two or more arrays and returns a new array, without changing the existing arrays.

arr1 = ['a','b','c'];
arr2 = ['d','e','f'];
console.log(arr1.concat(arr2)); // a,b,c,d,e,f

6. every( )

This method checks every element in the array that passes the condition, returning true or false as appropriate.

const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));//  true

7. some( )

This method checks if at least one element in the array that passes the condition, returning true or false accordingly

arr=[1,4,6,8];
l = arr.some(num => num > 7);
console.log(l);

8. includes( )

As above method check the condition but this method checks if an array includes the element that passes the condition, returning true or false as appropriate.

arr = [1,2,3,4,5,6];
console.log(arr.includes(2)); //true

9. join( )

This method returns a new string by concatenating all of the array’s elements separated by the specified separator.

arr = [ "hello ","world"];
console.log(arr.join('')); // hello world

10. reduce( )

In simple manner we can say this method applies a function against an accumulator and each element in the array to reduce it to a single value. In technical manner we can the reduce() method executes a user-supplied "reducer", It is a callback function on each element of the array, in order, passing in the return value of the calculations/operations.

const arr = [1,2,3,4,5];
const sum = arr.reduce((sum,current => sum + current));
console.log(sum); //15

11. find( )

This method returns the value of the first element in an array that pass the test in a testing function.

const arr = [1,2,4,6];
const ele = arr.find( elemt => elemt > 5);
console.log(ele); //6

12. findIndex( )

This method returns the index of the first element in an array that pass the test in a testing function.

const arr = [ 1,2,3,4,5];
const indexofele = arr.findIndex( ele => ele === 5);
console.log(indexofele);

13. indexOf( )

This method returns the index of the first occurrence of the specified element in the array, or -1 if it is not found.

const arr = ["hi", "bye", "like"];
cont indexof1stoccurance = arr.indexOf(elemt => elemt === 'like');
console.log(indexof1stoccurance ); // 2

14. fill()

The fill methord fills an array with a static values

const arr = new arr(3);
console.log(arr.fill(1));  [1,1,1]
const colors = ['red', 'blue', 'green'];
colors.fill('pink');
console.log(colors);  // ['pink','pink','pink']

15. reverse()

The reverse() method reverses the elements' positions in the array so that the last element goes into the first position and the first element goes to the last position.

const city = ['hyd', 'viz', 'tpty'];
names.reverse(); // returns ["hyd", "tpty", "viz"]

16. splice()

The splice() method helps you add, update, and remove elements in an array. It returns an array of the elements deleted and modifies the original array.

const names = ['java', 'python', 'ruby'];
const deleted = names.splice(2, 1, 'javascript');
console.log(deleted); // ["ruby"]
console.log(names); // ["java", "python", "javascript"]

17. at()

This method help you access the elements of an array using a negative index number and positive index number.

const fruits = ['Apples', 'Apricots', 'Avocados', 'Bananas', 'Boysenberries', 'Blueberries', 'Bing Cherry'];

fruits.at(0); //Apples
fruits .at(-1); Bing Cherry
fruits.at(-2); //Blueberries

18.unshift()

This method adds one or more elements to the beginning of an array and returns the new length of the array.

const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5)); //  5
console.log(array1);  // [4, 5, 1, 2, 3]

19.shift()

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1); /// output:  [2, 3]
console.log(firstElement); // 1

20.slice()

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2)); // ["camel", "duck", "elephant"]
console.log(animals.slice()); // ['ant', 'bison', 'camel', 'duck', 'elephant'];

This is the end I hope you all have got some idea on JavaScript Array Method's these are the most used functions while using arrays in JavaScript.