What are the methods of manipulating arrays in JavaScript

What are arrays in JavaScript?

Before you start, you need to understand the real meaning of arrays.

In JavaScript, an array is a variable used to store different data types. It stores different elements in a box for later use.

Declare an array:

let myBox = [];   //  Initialization array declaration in JS

An array can contain multiple data types

let myBox = ['hello', 1, 2, 3, true, 'hi'];

Arrays can be manipulated with multiple operations called methods. These methods allow us to add, delete, modify and perform more operations on the array.

I'll show you some of them in this article. Let's continue:

Note: the arrow function is used in this article. If you don't know what this means, you should read it here. The arrow function is the function of ES6.

toString()

toString()   Method converts an array to a comma separated string.

let colors = ['green', 'yellow', 'blue'];

console.log(colors.toString()); // green,yellow,blue

join()

The JavaScript   join()   Method combinations all array elements into a string. JavaScript   join()   Method combines all array elements into a string.

It is similar to   toString()   Method, but here you can specify a delimiter instead of the default comma.

let colors = ['green', 'yellow', 'blue'];

console.log(colors.join('-')); // green-yellow-blue

concat

This method can combine two arrays, or add more element items to the array, and then return a new array.

let firstNumbers = [1, 2, 3];
let secondNumbers = [4, 5, 6];
let merged = firstNumbers.concat(secondNumbers);
console.log(merged); // [1, 2, 3, 4, 5, 6]

push()

This method adds an element item to the end of the array and modifies the original array.

let browsers = ['chrome', 'firefox', 'edge'];
browsers.push('safari', 'opera mini');
console.log(browsers); 
// ["chrome", "firefox", "edge", "safari", "opera mini"]

pop()

This method deletes the last item of the array and returns.

let browsers = ['chrome', 'firefox', 'edge'];
browsers.pop(); // "edge"
console.log(browsers); // ["chrome", "firefox"]

shift()

This method deletes the first item of the array and returns it.

let browsers = ['chrome', 'firefox', 'edge'];
browsers.shift(); // "chrome"
console.log(browsers); // ["firefox", "edge"]

unshift()

This method adds an item to the beginning of the array and modifies the original array.

let browsers = ['chrome', 'firefox', 'edge'];
browsers.unshift('safari');
console.log(browsers); //  ["safari", "chrome", "firefox", "edge"]

You can also add multiple items at once

splice()

This method modifies the array by adding, deleting, and inserting elements.

The syntax is:

array.splice(index[, deleteCount, element1, ..., elementN])
  • Index   This is the starting point for deleting the elements in the array

  • deleteCount   Is the number of elements to remove from the index

  • element1, …, elementN   Is the element to add

delete item

*After running * * splice() *, it returns the array after deleting the item, and the deleted item deletes it from the original array.

let colors = ['green', 'yellow', 'blue', 'purple'];
colors.splice(0, 3);
console.log(colors); // ["purple"]
// deletes ["green", "yellow", "blue"]

Note: deleteCount does not include the last index in the range.

If the second parameter is not declared, all elements starting from the given index will be deleted from the array:

let colors = ['green', 'yellow', 'blue', 'purple'];
colors.splice(3);
console.log(colors); // ["green", "yellow", "blue"]
// deletes ['purple']

In the next example, we will delete three elements from the array and replace them with more items:

let schedule = ['I', 'have', 'a', 'meeting', 'tommorrow'];
// removes 4 first elements and replace them with another
schedule.splice(0, 4, 'we', 'are', 'going', 'to', 'swim');
console.log(schedule); 
// ["we", "are", "going", "to", "swim", "tommorrow"]

add item

To add items, we need to   deleteCount   Set to zero

let schedule = ['I', 'have', 'a', 'meeting', 'with'];
// adds 3 new elements to the array
schedule.splice(5, 0, 'some', 'clients', 'tommorrow');
console.log(schedule); 
// ["I", "have", "a", "meeting", "with", "some", "clients", "tommorrow"]

slice()

This method is a bit like splice(), but it is very different. It returns a subarray instead of a substring.

This method copies the given part of the array and returns the copied part as a new array. It does not change the original array.

The syntax is:

array.slice(start, end)

This is a simple example:

let numbers = [1, 2, 3, 4]
numbers.slice(0, 3)
// returns [1, 2, 3]
console.log(numbers) //Returns the original array

use   slice()   The best way is to assign it to a new variable.

let message = 'congratulations'
const abbrv = message.slice(0, 7) + 's!'; 
console.log(abbrv) //  return   "congrats!"

split()

This method is used for string. It divides a string into substrings and returns them as an array.

Syntax: string.split(separator, limit);

  • there   separator   Defines how to split strings.

  • Decided to divide it into several parts

let firstName = 'Bolaji';
// return the string as an array
firstName.split() // ["Bolaji"]

Another example:

let firstName = 'hello, my name is bolaji, I am a dev.';
firstName.split(',', 2); // ["hello", " my name is bolaji"]

Note: if we declare an empty array, such as   firstName.split('');, Then each item in the string will be split into substrings:

let firstName = 'Bolaji';
firstName.split('') // ["B", "o", "l", "a", "j", "i"]

indexOf()

This method looks for an item in the array, returns the index if it is found, otherwise returns  - one

let fruits = ['apple', 'orange', false, 3]
fruits.indexOf('orange'); // returns 1
fruits.indexOf(3); // returns 3
friuts.indexOf(null); // returns -1 (not found)

lastIndexOf()

This method works in the same way as   indexOf()   Same, but it works from right to left. It returns the last index found

let fruits = ['apple', 'orange', false, 3, 'apple']
fruits.lastIndexOf('apple'); // returns 4

filter()

If the items of the array meet a certain condition, this method will create a new array.

The syntax is:

let results = array.filter(function(item, index, array) {
  // returns true if the item passes the filter
});

Example: check users from Nigeria by area code

const countryCode = ['+234', '+144', '+233', '+234'];
const nigerian = countryCode.filter( code => code === '+234');
console.log(nigerian); // ["+234", "+234"]

map()

This method creates a new array by manipulating the values in the array.

Example: display the user name on the page. (basic friends list display)

const userNames = ['tina', 'danny', 'mark', 'bolaji'];
const display = userNames.map(item => {
 return '<li>' + item + '</li>';
})
const render = '<ul>' + display.join('') + '</ul>';
document.write(render);

Another example:

//  Adds the dollar sign to the front of the number
const numbers = [10, 3, 4, 6];
const dollars = numbers.map( number => '$' + number);
console.log(dollars);
// ['$10', '$3', '$4', '$6'];

reduce()

This method is used to calculate the value of the total.

reduce()   Used to calculate a single value in an array.

let value = array.reduce(function(previousValue, item, index, array) {
  // ...
}, initial);

Example:

To traverse the array and sum all the numbers in the array, you can use the for loop.

const numbers = [100, 300, 500, 70];
let sum = 0;
for (let n of numbers) {
 sum += n;
}
console.log(sum);

Here's how to use   reduce()   Method of realizing the same g function

const numbers = [100, 300, 500, 70];
const sum = numbers.reduce( (accummulator, value) =>
 accummulator + value
 , 0);
console.log(sum); // 970

If you omit the initial value, by default, the total is calculated from the first item in the array.

const numbers = [100, 300, 500, 70];
const sum = numbers.reduce((accummulator, value) => accummulator + value);
console.log(sum); // still returns 970

The following code snippet shows   reduce()   Method is used with all four parameters.

Source: MDN Docs

of

Source: MDN Docs

of   reduce()   More descriptions of the various uses of can be found here and here.

forEach()

This method applies to iterative arrays.

It acts on all items in the array

const colors = ['green', 'yellow', 'blue'];
colors.forEach((item, index) => console.log(index, item));
// returns the index and the every item in the array
// 0 "green"
// 1 "yellow"
// 2 "blue"

The iteration can be completed without passing index parameters

const colors = ['green', 'yellow', 'blue'];
colors.forEach((item) => console.log(item));
// returns every item in the array
// "green"
// "yellow"
// "blue"

every()

This method checks whether all items in the array meet the specified conditions. If so, it returns   true, otherwise return   false.

Check that all numbers are positive

const numbers = [1, -1, 2, 3];
let allPositive = numbers.every((value) => {
return value >= 0;
})
console.log(allPositive); // would return false

some()

This method checks whether the items (one or more) in the array meet the specified conditions. If so, it returns true; otherwise, it returns false.

Check that at least one number is positive

const numbers = [1, -1, 2, 3];
let atLeastOnePositive = numbers.some((value) => {
return value >= 0;
})
console.log(atLeastOnePositive); // would return true

includes()

This method checks whether the array contains an item. It is similar to  . some(), but instead of looking for specific conditions that match, it checks whether the array contains specific items.

let users = ['paddy', 'zaddy', 'faddy', 'baddy'];
users.includes('baddy'); // returns true

If the item is not found, returns   false

There is more about array methods, which is only part of it. In addition, there are a lot of other operations that can be performed on the array. Please see the MDN document for more in-depth information.

summary

  • toString()  - Converts an array to a comma separated string.

  • join()  - Combines all array elements into one string.

  • concat  - Combine two arrays together, or add more items to the array, and then return a new array.

  • push()  - Add an item to the end of the array and change the original array.

  • pop()  - Deletes the last item of the array and returns

  • shift()  - Delete the first item of the array and return

  • unshift()  - Add an item to the beginning of the array and change the original array.

  • splice()  - Modify an array by adding, deleting, and inserting elements.

  • slice()  - Copies the given part of the array and returns the copied part as a new array. It does not change the original array.

  • split()  - Divides a string into substrings and returns them as an array.

  • indexOf()  - Finds an item in an array and returns its index, or - 1 if it is not found

  • lastIndexOf()  - Finds items from right to left and returns the last index found.

  • filter()  - If the items of the array meet a certain condition, a new array is created.

  • map()  - Create a new array by manipulating the values in the array.

  • reduce()   - The calculation is based on a single value in the array.

  • forEach()  - Traverse the array and apply the function to all items in the array

  • every()  - Checks whether all items in the array meet the specified conditions. If so, returns   true, otherwise return   false.

  • some()  - Check whether the items (one or more) in the array meet the specified conditions. If so, return true; otherwise, return false.

  • includes()  - Check whether the array contains an item.

Arrays are powerful, and practical algorithms can be written through related methods.

Let's write a small function, a function that converts the article title to urlSlug.

URL slug is the exact address of a specific page or article on your website.

When you are   Freecodecamp News   Or any other blog platform, your article title will be automatically converted to a slug, in which spaces are deleted, characters become lowercase, and each word in the title is separated by hyphens.

This is a basic function, which can be achieved by using some methods we have just learned.

const url = 'https://bolajiayodeji.com/'
const urlSlug = (postTitle) => {
let postUrl = postTitle.toLowerCase().split(' ');
let postSlug = `${url}` + postUrl.join('-');
return postSlug;
}
let postTitle = 'Introduction to Chrome Lighthouse'
console.log(urlSlug(postTitle));
// https://bolajiayodeji.com/introduction-to-chrome-lighthouse

stay   postUrl   In, we first convert the string to lowercase, and then use   split()   Method converts a string to a substring and returns it to an array

["introduction", "to", "chrome", "lighthouse"]

stay   post slug   Concatenate the returned array with a hyphen, and then combine it with the category string and the main string   url   Connect together.

let postSlug = `${url}` + postUrl.join('-');
postUrl.join('-') // introduction-to-chrome-lighthouse

That's it. It's very simple, isn't it? 😄

Tags: Javascript html5 html

Posted on Sat, 02 Oct 2021 16:00:01 -0400 by reflash