Header Ads Widget

JavaScript Array - Everything you need to know

 


This blog post will cover the concepts of Arrays in JavaScript and different ways to manipulate Arrays in JavaScript.



Introduction

Objects normally allow to store keyed collection of values, but when it is required to store ordered collection, then JavaScript will come into the picture. JavaScript Array is a special variable, which can hold more than one value (of different types) at a time.

Declaration

There are basically two syntaxes for creating an empty array.

//Option 1
var names = ["James", "Robert", "Shane"];

//Option 2
var names;
names = ["James", "Robert", "Shane"];



Navigation

Below are the different ways to iterate through the array using indexes.

var names = ["James", "Robert", "Shane"];

//Option 1
for (let i = 0; i < names.length; i++) {
console.log(names[i]);
}

//Option 2
for (let singleName of names) {
console.log(singleName);
}

//Option 3
for (let index in names) {
console.log(names[index]);
}

//Option 4
names.forEach((singleName) => {
console.log(singleName.toUpperCase());
});



Finding Array Elements

Below methods are mainly used to find elements in Array.

includes()

This method will return true if the specified value is present in the array, otherwise, it will pass false.


Code snippet:
function checkFruits(fruitName) {
let fruits = ["Banana", "Orange", "Apple", "Mango"];
return fruits.includes(fruitName);
}

console.log("Includes Banana: " + checkFruits("Banana"));
console.log("Includes Grape: " + checkFruits("Grape"));
Output:
[Running] node "/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js"
Includes Banana: true
Includes Grape: false


indexOf()

This method will return the first index of the specified value if the specified value is present in the array, otherwise, it will return -1.


Code snippet:
function checkFruits(fruitName) {
let fruits = ["Banana", "Orange", "Apple", "Mango"];
return fruits.indexOf(fruitName);
}

console.log("indexOf Apple: " + checkFruits("Apple"));
console.log("indexOf Grape: " + checkFruits("Grape"));
Output:
[Running] node "/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js"
indexOf Apple: 2
indexOf Grape: -1 


lastIndexOf()

This method will return the last index of the specified value if the specified value is present in the array, otherwise, it will return -1.


Code snippet:
function checkFruits(fruitName) {
let fruits = ["Banana", "Orange", "Apple", "Mango", "Apple", "Banana"];
return fruits.lastIndexOf(fruitName);
}

console.log("lastIndexOf Apple: " + checkFruits("Apple"));
console.log("lastIndexOf Banana: " + checkFruits("Banana"));
console.log("lastIndexOf Grape: " + checkFruits("Grape"));
Output:
[Running] node "/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js"
lastIndexOf Apple: 4
lastIndexOf Banana: 5
lastIndexOf Grape: -1
 

findIndex()

This method will return the index of the first element which satisfies the condition, otherwise, it will return -1.


Code snippet:
function checkAmountGreaterThan(value) {
let amount = [12, 25, 78, 29, 76, 98, 105];
return amount.findIndex((singleAmount) => singleAmount > value);
}

console.log(
"findIndex where amount is greater than 50: " + checkAmountGreaterThan(50)
);
console.log(
"findIndex where amount is greater than 100: " + checkAmountGreaterThan(100)
);
console.log(
"findIndex where amount is greater than 500: " + checkAmountGreaterThan(500)
);
Output:
[Running] node "/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js"
findIndex where amount is greater than 50: 2
findIndex where amount is greater than 100: 6
findIndex where amount is greater than 500: -1
 
 

find()

This method will return the value of the first element which satisfies the condition, otherwise, it will return undefined.


Code snippet:
function checkAmountGreaterThan(value) {
let amount = [12, 25, 78, 29, 76, 98, 105];
return amount.find((singleAmount) => singleAmount > value);
}

console.log(
"find where amount is greater than 50: " + checkAmountGreaterThan(50)
);
console.log(
"find where amount is greater than 100: " + checkAmountGreaterThan(100)
);
console.log(
"find where amount is greater than 500: " + checkAmountGreaterThan(500)
);
Output:
[Running] node "/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js"
find where amount is greater than 50: 78
find where amount is greater than 100: 105
find where amount is greater than 500: undefined
 
 

Merging/Joining Arrays

concat()

This method can be used to merge multiple arrays. It will return a new array with merged contents without modifying the original arrays.


Code snippet:
let country1 = ["India", "Canada", "Singapore"];
let country2 = ["Switzerland", "United States of America", "Norway"];

let mergedCountry = country1.concat(country2);
console.log("mergedCountry: " + mergedCountry);
Output:
[Running] node "/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js"
mergedCountry: India,Canada,Singapore,Switzerland,United States of America,Norway
 

join()

This method can be used to join all the elements of the array separated by commas or the separator specified. It will return a new string without modifying the original arrays.


Code snippet: 
let country = [
"India",
"Canada",
"Singapore",
"Switzerland",
"United States of America",
"Norway",
];

let joinedCountry = country.join(" <=> ");
console.log("joinedCountry: " + joinedCountry);
Output:
[Running] node "/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js"
joinedCountry: India <=> Canada <=> Singapore <=> Switzerland <=> United States of America <=> Norway



Sort Arrays

sort()

This method can be used to sort elements of an array. By default, it will do the sorting in ascending order, but an optional parameter can be used to define the sort order. To understand sort method in details, please read the post - Sorting Arrays in JavaScript


Code snippet:
let employees = [
{ name: "James Bond", empNumber: 98 },
{ name: "Jacky Jones", empNumber: 76 },
{ name: "Kelly Ditner", empNumber: 24 },
{ name: "Jonathan Patel", empNumber: 56 },
];

let sortEmployees1 = employees.sort();
console.log("Printing sortEmployees1");
sortEmployees1.forEach((singleEmployee) => {
console.log(
"Name: " +
singleEmployee.name +
" Employee Number: " +
singleEmployee.empNumber
);
});

let sortEmployees2 = employees.sort((a, b) => a.empNumber - b.empNumber);
console.log("Printing sortEmployees2");
sortEmployees2.forEach((singleEmployee) => {
console.log(
"Name: " +
singleEmployee.name +
" Employee Number: " +
singleEmployee.empNumber
);
});
Output:
[Running] node "/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js"
Printing sortEmployees1
Name: James Bond Employee Number: 98
Name: Jacky Jones Employee Number: 76
Name: Kelly Ditner Employee Number: 24
Name: Jonathan Patel Employee Number: 56
Printing sortEmployees2
Name: Kelly Ditner Employee Number: 24
Name: Jonathan Patel Employee Number: 56
Name: Jacky Jones Employee Number: 76
Name: James Bond Employee Number: 98


reverse()

This method can be used to reverse the array by changing the original array. This method will return the reversed array.


Code snippet:
let employees = [
{ name: "James Bond", empNumber: 98 },
{ name: "Jacky Jones", empNumber: 76 },
{ name: "Kelly Ditner", empNumber: 24 },
{ name: "Jonathan Patel", empNumber: 56 },
];

let reverseEmployee = employees.reverse();
console.log("Printing reverseEmployee");
reverseEmployee.forEach((singleEmployee) => {
console.log(
"Name: " +
singleEmployee.name +
" Employee Number: " +
singleEmployee.empNumber
);
});
Output:
[Running] node "/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js"
Printing reverseEmployee
Name: Jonathan Patel Employee Number: 56
Name: Kelly Ditner Employee Number: 24
Name: Jacky Jones Employee Number: 76
Name: James Bond Employee Number: 98


Advanced Functions

map()

This method will map each element of the array to something else. This method will require a callback function that will take three parameters (currentValue - this is mandatory,  index and array). Finally, it will return an array.


Code snippet:
let employees = [
{ name: "James Bond", empNumber: 98 },
{ name: "Jacky Jones", empNumber: 76 },
{ name: "Kelly Ditner", empNumber: 24 },
{ name: "Jonathan Patel", empNumber: 56 },
];

const employeesInUpperCase = employees.map((singleEmployee) => {
return singleEmployee.name.toUpperCase();
});

console.log("employeesInUpperCase: " + employeesInUpperCase);
Output:
[Running] node "/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js"
employeesInUpperCase: JAMES BOND,JACKY JONES,KELLY DITNER,JONATHAN PATEL


filter()

This method will test each element of the array with the filter criteria. This method will require a callback function that will take three parameters (currentValue - this is mandatory,  index and array). Finally, it will return an array.


Code snippet:
let employees = [
{ name: "James Bond", empNumber: 98 },
{ name: "Jacky Jones", empNumber: 76 },
{ name: "Kelly Ditner", empNumber: 24 },
{ name: "Jonathan Patel", empNumber: 56 },
];

const filterEmployee = employees.filter((singleEmployee) => {
return singleEmployee.empNumber >= 50;
});
filterEmployee.forEach((singleEmployee) =>
console.log(
"Name: " + singleEmployee.name + " EmplNumber: " + singleEmployee.empNumber
)
);
Output:
[Running] node "/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js"
Name: James Bond EmplNumber: 98
Name: Jacky Jones EmplNumber: 76
Name: Jonathan Patel EmplNumber: 56

reduce()

This method will work on each element of the array and reduce it to one single value based on the logic written in the callback function. This method will require a callback function that will take two parameters (accumulator and currentValue), then the second parameter is the current index or initial value of the accumulator and the final parameter is the array. Finally, it will return an array.


Code snippet:
let employees = [
{ name: "James Bond", expense: 98 },
{ name: "Jacky Jones", expense: 76 },
{ name: "Kelly Ditner", expense: 24 },
{ name: "Jonathan Patel", expense: 56 },
];

let totalExpense = employees.reduce((accumulator, currentValue) => {
return accumulator + currentValue.expense;
}, 0);

console.log("totalExpense: " + totalExpense);

let words = ["Hello", "Canada", "How", "are", "you", "?"];
let sentence = words.reduce(
(accumulator, currentValue) => accumulator + " " + currentValue
);

console.log("sentence: " + sentence);
Output:
[Running] node "/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js"
totalExpense: 254
sentence: Hello Canada How are you ?

flat()

This method will work on subarrays and flatten them to make them a single array. You can specify the depth of flattening as an argument for the flat method.


Code snippet:
let numbers1 = [10, 34, 67, [1, 23, 12]];
let flattenNumbers1 = numbers1.flat();
console.log(flattenNumbers1);

let numbers2 = [10, 34, 67, [1, 23, 12, [56, 78, 100]]];
let flattenNumbers2 = numbers2.flat(2);
console.log(flattenNumbers2);
Output:
[Running] node "/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js"
[ 10, 34, 67, 1, 23, 12 ]
[ 10, 34, 67, 1, 23, 12, 56, 78, 100 ]


every()

This method will work on every element of the array and will return true or false based on whether every element passes the condition mentioned.


Code snippet:
let numbers1 = [10, 34, 67, 1, 23, 12];
console.log(numbers1.every((singleNumber) => singleNumber > 0));
console.log(numbers1.every((singleNumber) => singleNumber > 10));
Output:
[Running] node "/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js"
true
false


some()

This method will work on every element of the array and will return true or false based on whether at least one element passes the condition mentioned.


Code snippet:
let numbers1 = [10, 34, 67, 1, 23, 12];
console.log(numbers1.some((singleNumber) => singleNumber > 200));
console.log(numbers1.some((singleNumber) => singleNumber > 50));
Output:
[Running] node "/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js"
false
true


spread()

This operator allows an iterable such as an array expression or string to expand where the number of arguments expected is dynamic. It can be 0, 1, or 100. It is mostly used in variable arrays.


Code snippet:
function doSum(a, b, c) {
return a + b + c;
}

let numbers = [1, 4, 5, 8, 2];
console.log(doSum(...numbers));
Console:
[Running] node "/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js"
10


rest()

Rest is the way to handle function parameters, allowing more easily to handle various inputs as parameters in the function. The syntax is the same as spread.


Code snippet:
function doSum(...args) {
let sum = args.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
return sum;
}

console.log(doSum(1, 4, 5, 8, 2));
Output:
[Running] node "/Users/sudipta/Documents/CodeBase/JavaScript/src/Arrays.js"
20




Post a Comment

0 Comments