Understand the Array in JS 

Similar to arrays in other programming languages, the Array object permits the storage of a collection of various elements under a single variable name and provides members for carrying out standard array operations.

1. forEach

For each element in an array, the forEach() method performs the specified function once.

For each entry in an array, in ascending index order, forEach() calls the callbackFn function supplied once. When an index property is uninitialized or deleted, it is not called.

array.forEach(callback[, thisObject]);
const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"

2. map

Using a callback function, you can iterate through an array's elements using the Array.map() method. The items of the array will then each receive an execution of the callback function.

array.map(callback[, thisObject]);

let arr = [3, 4, 5, 6];

let modifiedArr = arr.map(function(element){
    return element *3;
});

console.log(modifiedArr); // [9, 12, 15, 18]

The Array.map() method is frequently used to make modifications to the elements, whether you want to multiply by a certain amount, like in the code above, or do any other operations that your application might need.

3. concat

In JavaScript, concat() is a string method that is used to append one or more strings together. The concat() method appends one or more string values to the calling string and then returns the concatenated result as a new string.

Concat() is a String method, and therefore must be called through a particular instance of the String class.

array.concat(value1, value2, ..., valueN);


const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]

4. push

The array push() method in Javascript appends the specified element(s) to the end of the array and returns the length of the new array.
Push is used to add an element to the end of an array ().

array.push(element1, ..., elementN);


const countries = ["Nigeria", "Ghana", "Rwanda"];
countries.push("Kenya");
console.log(countries); // ["Nigeria","Ghana","Rwanda","Kenya"]

5. pop

The pop() function returns the value of the last element removed from an array to the caller. When called on an empty array, pop() returns undefined.

Array.prototype.

The behavior of shift() is identical to that of pop(), but it is applied to the first element of an array.

array.pop();

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// expected output: "tomato"

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

6. splice

The splice() function is a general-purpose technique that can be used to change the contents of an array by removing, replacing, or adding components in defined points. This section will explain how to apply this strategy to a specific area.

array.splice(index, howMany, [element1][, ..., elementN]);


const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi"); //Banana,Orange,Lemon,Kiwi,Apple,Mango

7. slice

The slice() method returns a shallow copy of a piece of an array into a new array object chosen from start to end (end not included), where start and end indicate the indexes of the array's members. The original array will remain unchanged.

array.slice( begin [,end] );

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

8. shift

shift() is a JavaScript built-in function that removes the first element from an array. The shift() function affects the JavaScript array with which you are working directly. shift() returns the item from the array that you deleted.

The shift() function deletes the item at index position 0 and reduces the values at subsequent index numbers by one.

array.shift();

const array1 = [1, 2, 3];

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

9. unshift

The unshift() method puts the specified values at the start of an array-like object.

Array.prototype.Push() behaves similarly to unshift(), but it is applied to the end of an array.

array.unshift( element1, ..., elementN );

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

10. join

JavaScript array join() is a built-in method that concatenates all of the array's components to construct and return a new string. The join() method merges the array's contents into a string and returns it. The array of elements will be separated by the separator given. A comma is the default separator (,).

array.join(separator);


const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join());
// expected output: "Fire,Air,Water"
console.log(elements.join(''));
// expected output: "FireAirWater"
console.log(elements.join('-'));
// expected output: "Fire-Air-Water"

11. every

The every() method determines whether all array elements pass the test implemented by the provided function. It yields a Boolean value.

array.every(callback[, thisObject]);

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

12. filter

The filter() method returns a shallow duplicate of a piece of a given array that has been filtered down to only the elements of the given array that pass the test defined by the provided function.

array.filter(callback[, thisObject]);


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

13. indexOf

The indexOf() method returns the first index in the array at which a specified element can be found, or -1 if it does not exist.

array.indexOf(searchElement[, fromIndex]);


const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1

14. reduce

The reduce() method calls a user-supplied "reducer" callback function on each element of the array in turn, sending in the result of the previous element's calculation. The outcome of running the reducer across all array elements is a single value.

array.reduce(callback[, initialValue]);

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial)

15. reverse

The reverse() method reverses an array in place and returns a reference to it, with the first array element becoming the last and the last array element becoming the first. In other words, the array's element order will be flipped in the opposite direction as previously mentioned.

array.reverse();


const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// expected output: "array1:" Array ["three", "two", "one"]

16. sort

The sort() method sorts an array's items in situ and returns a reference to the sorted array. The ascending sort order is created by turning the elements into strings and then comparing their sequences of UTF-16 code unit values.

array.sort( compareFunction );


const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

17. toString

The function toString() { [native code] }() method returns a string containing the object's name.

array.toString();


function Dog(name) {
  this.name = name;
}

const dog1 = new Dog('Gabby');

Dog.prototype.toString = function dogToString() {
  return `${this.name}`;
};

console.log(dog1.toString());
// expected output: "Gabby"

18. at

The at() method accepts an integer value and returns the item at that index, which can be positive or negative. Negative integers count backwards from the array's last member.

array.at(index)


const array1 = [5, 12, 8, 130, 44];

let index = 2;

console.log(`Using an index of ${index} the item returned is ${array1.at(index)}`);
// expected output: "Using an index of 2 the item returned is 8"

index = -2;

console.log(`Using an index of ${index} item returned is ${array1.at(index)}`);
// expected output: "Using an index of -2 item returned is 130"

19. find

The find() method returns the first element in the specified array that meets the testing function. Undefined is returned if no values satisfy the testing function.

array.find(function(currentValue, index, arr),thisValue)


const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

20. some

The some() method determines whether at least one array element passes the test implemented by the provided function. It returns true if it finds an element in the array for which the specified function returns true; otherwise, it returns false. It makes no changes to the array.

array.some(callback[, thisObject]);


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

// checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// expected output: true

Recommended Posts

View All

How to Get Current URL in Laravel


how to get current url in laravel, laravel get current url, get current page url in laravel, get full url in laravel, find current url in laravel,

Laravel 9 Install React Auth Tutorial with Example


In this article, I'll demonstrate how to use the Laravel UI and React Auth scaffolding to create login, register, logout, forget password, profile, an...

Laravel One to Many Eloquent Relationship


laravel one to many relationship example, laravel one to many sync, one to many relationship laravel 5.6, one to many relationship laravel model

Laravel Query Builder Where Exists Example


laravel use sql where exists clause,laravel whereExists, laravel whereExists not working,laravel where exists example,laravel exists query

Laravel where clause with date_format() example


laravel db raw where, laravel where date_format, laravel date_format mysql where, laravel date_format example, laravel where with month