Working With Javascript Array

Md. Abu Talha
InfancyIT
Published in
5 min readOct 31, 2018
Photo by Paweł Czerwiński on Unsplash

When we work with the javascript array, we need to handle many things for work purpose. In this article, I’ll try to discuss the basic use of array in javascript.

Array Generate:

const numbersArray = [] , max = 100;
for( var i=1; numbersArray.push(i++) < max;);

Accessing Elements:

const alphas = ["1","2","3","4"] 
console.log(alphas[0]); //1
console.log(alphas[1]); //2

Get Random Item:

const items = [152, 5458 , 111 , 277 , 5478 , 333];
let randomItem = items[Math.floor(Math.random() * items.length)];

Suffle an Array:

const numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
numbers = numbers.sort(() => Math.random() - 0.5);

Array Sort:

const numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
numbers = numbers.sort();

Array Concat:

Returns a new array

const alpha = ["a", "b", "c"]; 
const numeric = [1, 2, 3];
const alphaNumeric = alpha.concat(numeric);
console.log(alphaNumeric); //["a", "b", "c", 1, 2, 3]

Append Array:

const array1 = [12 , "jon", -24758];
const array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
console.log(array1) //[12, "hon", -24758, "Doe", 555, 100]

or using ES6 spread function - Returns a new array

const arr1 = [1,2,3]
const arr2 = [4,5,6]
const arr3 = [...arr1, ...arr2]
console.log(arr3) //[1, 2, 3, 4, 5, 6]

Verify the given Argument is an Array:

Array.isArray(obj);

Max an Min form an Array:

const  numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205]; 
let maxInNumbers = Math.max.apply(Math, numbers);
let minInNumbers = Math.min.apply(Math, numbers);

Empty an Array:

const myArray = [12 , 222 , 1000 ];  
myArray.length = 0;

Removes Multiple Items Using Array Length:

var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];  
myArray.length = 4;
console.log(myArray) //[12 , 222 , 1000 , 124]

Find Index for Array of Item:

indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

const array1 = [12, 5, 8, 130, 8]
let index = array1.indexOf(8);
console.log("index is : " + index) //"index is : 2"

lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backward, starting at fromIndex.

let index = array1.lastIndexOf(8); 
console.log("index is : " + index) //"index is : 4"

Filter:

filter() method creates a new array with all elements that pass the test implemented by the provided function.

const array1 = [12, 5, 8, 130, 44]
let isBigEnough = (element) => (element >= 10)
let newArray = array1.filter(isBigEnough);
console.log(newArray ); //[12, 130, 44]

Map:

map() method creates a new array with the results of calling a provided function on every element in this array.

const numbers = [1, 4, 9]
const roots = numbers.map(Math.sqrt)
console.log(roots)//[1, 2, 3]
const arr = [1, 2, 3, 4, 5]
const arr2 = arr.map(num => num * 2)
console.log(arr2)//[2, 4, 6, 8, 10]
const arr2 = arr.map(num => num * 2).filter(num => num > 5)
//[6, 8, 10]

Reduce:

Returns the reduced single value of the array.

As the name already suggest reduce method of the array object is used to reduce the array to one single value.

reduce() method applies a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.

const arr = [1, 2, 3, 4, 5]
let total = arr.reduce((a, b) => a + b)
console.log("total is : " + total ) //"total is : 15"

reduceRight() method applies a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.

const arr = [1, 2, 3, 4, 5]
let total = arr.reduceRight((a, b) => a + b)
console.log("total is : " + total ); //"total is : 15"

Reverse:

const arr = [1, 2, 3, 4, 5]
arr.reverse()
console.log(arr) //[5, 4, 3, 2, 1]

Pop:

pop() method removes the last element from an array and returns that element.

const numbers = [1, 4, 9]; 
let element = numbers.pop();
console.log("element is : " + element ) //9

Shift:

shift()method removes the first element from an array and returns that element.

const arr = [1, 2, 3, 4, 5]
let val = arr.shift()
console.log("Shifted value is : " + val) //1
console.log(arr) //[2, 3, 4, 5]

Push:

push() method adds one or more elements to the last of an array and returns the new length of the array.

const arr = [1, 2, 3, 4, 5]
arr.push(222)
console.log( arr) //[1, 2, 3, 4, 5, 222]

Unshift:

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

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

Splice:

splice() method changes the content of an array, adding new elements while removing old elements.

array.splice(index, howMany, [element1][, ..., elementN]);
  • index − Index at which to start changing the array.
  • howMany − An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed.
  • element1, …, elementN − The elements to add to the array. If you don’t specify any elements, splice simply removes the elements from the array.

adding a new value in a specific index position,

const arr = ["orange", "mango", "banana", "sugar", "tea"]
arr.splice(2, 0, "water")
console.log(arr)
//["orange", "mango", "water", "banana", "sugar", "tea"]

adding a new value by deleting the previous one,

const arr = ["orange", "mango", "banana", "sugar", "tea"]
arr.splice(2, 1, "water")
console.log(arr) //["orange", "mango", "water", "sugar", "tea"]

delete an item,

const arr = ["orange", "mango", "banana", "sugar", "tea"]
arr.splice(3, 1)
console.log(arr) //["orange", "mango", "banana", "tea"]

or delete the whole items from the given index,

const arr = ["orange", "mango", "banana", "sugar", "tea"]
arr.splice(3)
console.log(arr) //["orange", "mango", "banana"]

delete all the data from an array[empty array],

const arr = ["orange", "mango", "banana", "sugar", "tea"]
const newArr = arr.splice()
console.log(newArr) // []

Slice:

slice() method extracts a section of an array and returns a new array.

array.slice( begin [,end] )
  • begin − Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence.
  • end − Zero-based index at which to end extraction.

Getting Items by given index range,

const arr = ["orange", "mango", "banana", "sugar", "tea"] 
const newArr = arr.slice(1,4)
console.log(newArr) //["mango", "banana", "sugar"]

getting items from the given index,

const arr = ["orange", "mango", "banana", "sugar", "tea"] 
const newArr = arr.slice(2)
console.log(newArr) //["banana", "sugar", "tea"]

cloning an array,

const arr = ["orange", "mango", "banana", "sugar", "tea"] 
const newArr = arr.slice()
console.log(newArr) //["orange", "mango", "banana", "sugar", "tea"]

Includes:

Checks if an array contains a certain value or not. It returns a boolean value.

const ratings = [3, 5, 4, 9, 5];
const includesRating = ratings.includes(9);
console.log(includesRating) // true

Some:

Check if there is at least one value in an array. Similar to .includes()

const ratings = [3, 5, 4, 9, 5];
const goodOverallRating = ratings.some( rating => rating === 8 );
console.log(goodOverallRating) // false

Every:

Similar to .some(), but checks if all items in an array pass a condition.

const ratings = [3, 5, 4, 9, 5];
const goodOverallRating = ratings.every( rating => rating >= 3 );
console.log(goodOverallRating) // true

toString:

toString() method returns a string representing the source code of the specified array and its elements.

const arr = ["orange", "mango", "banana", "sugar", "tea"] 
const newArr = arr.toString()
console.log(newArr) //"orange,mango,banana,sugar,tea"

--

--