Array

The Array object, enables storing a collection of multiple items under a single variable name. And has members for performing common array operations.

Mutable

Adds element at the end of array. And returns the new length of the array.

Syntax:

push()
push(element1)
push(element1, element2, /* …, */ elementN)

Example 1:

const sports = ["soccer", "baseball"];
const total = sports.push("football", "swimming");

console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
console.log(total); // 4

Example 2: Merging two arrays

const vegetables = ["parsnip", "potato"];
const moreVegs = ["celery", "beetroot"];

// Merge the second array into the first one
vegetables.push(...moreVegs);

console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']

Adds element at the beginning of array. And returns the new length of the array.

Syntax:

unshift()
unshift(element1)
unshift(element1, element2, /* …, */ elementN)

Example 1:

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]

Example 2:

  
const arr = [1, 2];

arr.unshift(0); // result of the call is 3, which is the new array length
// arr is [0, 1, 2]

arr.unshift(-2, -1); // the new array length is 5
// arr is [-2, -1, 0, 1, 2]

arr.unshift([-4, -3]); // the new array length is 6
// arr is [[-4, -3], -2, -1, 0, 1, 2]

arr.unshift([-7, -6], [-5]); // the new array length is 8
// arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]

Removes last element. And returns removed element

Syntax:

pop()

Example 1:

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

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

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

Removes first element. And returns removed element

Syntax:

shift()

Example 1:

const myFish = ["angel", "Gold fish", "Guppy fish"];

const shifted = myFish.shift();

console.log("Removed this element:", shifted);
// Removed this element: angel

console.log("myFish after:", myFish);
// myFish after: ["Gold fish", "Guppy fish"]

Example 2: Using shift() method in while loop

const names = ["Karthi", "Leo Das", "Herold Das", "Ronaldo", "Socrates"];

while (typeof (i = names.shift()) !== "undefined") {
    console.log(i);
}
// "Karthi", "Leo Das", "Herold Das", "Ronaldo", "Socrates"

Insertion and removal inbetween an array. And returns deleted elements

Syntax:

splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1, item2, /* …, */ itemN)

Example 1:

const months = ["Jan", "Feb", "Masi", "Margazhi", "Apr"];
const removed = months.splice(2, 2, "Mar");

console.log(removed); // ['Masi', 'Margazhi']

console.log(months); // ['Jan', 'Feb', 'Mar', 'Apr']

Example 2: Remove 0 (zero) elements and insert "drum" and "guitar"

const instruments = ["flute", "Mouthorgan", "keyboard"];
const removed = instruments.splice(1, 0, "drum", "guitar");

// instruments is['flute', 'drum', 'guitar', 'Mouthorgan', 'keyboard']
// removed is [], no elements removed

Used to Sort an array in some order. Sorts by Default in Alphebatic order

To make Custom sort order put a compare function inside it

Returns the sorted (mutated array)

Syntax:

sort()
sort(compareFn)

Example 1: Alphabetic order

const fruits = ['Orange', 'Pomogranate', 'Guava', 'Apple'];
fruits.sort();
console.log(fruits); // ['Apple', 'Guava', 'Orange', 'Pomogranate']

Example 2: Numerical assending order

const points = [40, 100, 1, 5, 25, 10];
points.sort( function(a, b){return a - b} );

console.log(points);
//[1, 5, 10, 25, 40, 100]

Example 3: Sorting Object Arrays

const cars = [
    {type:"Volvo", year:2016},
    {type:"Saab", year:2001},
    {type:"BMW", year:2010}
];

cars.sort(function(a, b){return a.year - b.year});

//{type: 'Saab', year: 2001}
//{type: 'BMW', year: 2010}
//{type: 'Volvo', year: 2016}

Example 4: Sorting Object Arrays - Comparing string properties is a little more complex

const cars = [
    {type:"Volvo", year:2016},
    {type:"Saab", year:2001},
    {type:"BMW", year:2010}
];

displayCars();

function myFunction() {
    cars.sort(function(a, b){
        let x = a.type.toLowerCase();
        let y = b.type.toLowerCase();
        if (x < y) {return -1;}
        if (x > y) {return 1;}
        return 0;
    });
    displayCars();
}

function displayCars() {
    document.getElementById("demo").innerHTML =
    cars[0].type + " " + cars[0].year + "
" + cars[1].type + " " + cars[1].year + "
" + cars[2].type + " " + cars[2].year; }

Example 5: Stable Array sort()

const myArr = [
    {name:"X00",price:100 },
    {name:"X01",price:100 },
    {name:"X02",price:100 },
    {name:"X03",price:100 },
    {name:"X04",price:110 },
    {name:"X05",price:110 },
    {name:"X06",price:110 },
    {name:"X07",price:110 },
    {name:"X08",price:120 },
    {name:"X09",price:120 },
    {name:"X10",price:120 },
    {name:"X11",price:120 },
    {name:"X12",price:130 },
    {name:"X13",price:130 },
    {name:"X14",price:130 },
    {name:"X15",price:130 },
    {name:"X16",price:140 },
    {name:"X17",price:140 },
    {name:"X18",price:140 },
    {name:"X19",price:140 }
];

myArr.sort( (p1, p2) => {
    if (p1.price < p2.price) return -1;
    if (p1.price > p2.price) return 1;
    return 0;
});

Example 6: Sorting in Random Order

const points = [40, 100, 1, 5, 25, 10];
points.sort(function(){return 0.5 - Math.random()});

Example 7: The Fisher Yates Method for Random sort

The above example, array.sort(), is not accurate. It will favor some numbers over the others.

The most popular correct method, is called the Fisher Yates shuffle, and was introduced in data science as early as 1938!

In JavaScript the method can be translated to this:

Click the button (again and again) to sort the array in random order.

const points = [40, 100, 1, 5, 25, 10]; 

function myFunction() {
    for (let i = points.length -1; i > 0; i--) {
        let j = Math.floor(Math.random() * (i+1));
        let k = points[i];
        points[i] = points[j];
        points[j] = k;
    }
    console.log(points);
}

document.getElementById("demo").addEventListener("click", myFunction);

Immutable

Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list.

There are three distinct places that accept the spread syntax:

  • Function arguments list (myFunction(a, ...iterableObj, b))
  • Array literals ([1, ...iterableObj, '4', 'five', 6])
  • Object literals ({ ...obj, key: 'value' })

Syntax:

(...)

Example 1: Quickly copies all or part of an existing array/object into another array/object.

const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];

Example 2: We can use the spread operator with objects too:

const myVehicle = {
    brand: 'Ford',
    model: 'Mustang',
    color: 'red'
  }
  
  const updateMyVehicle = {
    type: 'car',
    year: 2021, 
    color: 'yellow'
  }
  
  const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}

  console.log(myUpdatedVehicle);
  //{brand: 'Ford', model: 'Mustang', color: 'yellow', type: 'car', year: 2021}

Example 3: The spread operator is often used in combination with destructuring.

const numbers = [1, 2, 3, 4, 5, 6];

const [one, two, ...rest] = numbers;

console.log(one); //1
console.log(two); //2
console.log(rest); //[3, 4, 5, 6]

Example 4: Spreading array into object

const array = [1, 2, 3];
const obj = { ...array }; // { 0: 1, 1: 2, 2: 3 }

Note: Only iterable values, like Array and String, can be spread in array literals and argument lists. Many objects are not iterable, including all plain objects that lack a Symbol.iterator method:

const obj = { key1: "value1" };
const array = [...obj]; 
// TypeError: obj is not iterable

Example 5: Spreading String

let st = "Text";
let ar = [...st];
console.log(ar); //['T', 'e', 'x', 't'];

let ob = {...st}
console.log(ob); //{0: 'T', 1: 'e', 2: 'x', 3: 't'}

Note: All primitives can be spread in objects. Only strings have enumerable own properties, and spreading anything else doesn't create properties on the new object.


Example 6: Spread in function calls

function myFunction(x, y, z) {}
const args = [0, 1, 2];

myFunction(...args);
//-----------------------------------

function myFunction(a, b, c, d, e) {}
const args = [0, 1];

myFunction(-1, ...args, 2, ...[3]);

Example 7: Apply for new operator

const dateFields = [1970, 0, 1]; // 1 Jan 1970
const da = new Date(...dateFields);   
//Thu Jan 01 1970 00:00:00 GMT+0530 (IST) 

Example 8: Conditionally adding values to an array

You can make an element present or absent in an array literal, depending on a condition, using a conditional operator.

const isSummer = false;
const fruits = ["apple", "banana", ...(isSummer ? ["watermelon"] : [])];
// ['apple', 'banana']

Example 9:

const obj1 = { foo: "bar", x: 42 };
const obj2 = { foo: "baz", y: 13 };

const mergedObj = { x: 41, ...obj1, ...obj2, y: 9 }; 
// { x: 42, foo: "baz", y: 9 } 

Example 10: Conditionally adding properties to an object

const isSummer = false;
const fruits = {
    apple: 10,
    banana: 5,
    ...(isSummer ? { watermelon: 30 } : {}),
};
// { apple: 10, banana: 5 }

all falsy values do not have enumerable properties, you can simply use a logical AND operator:

const isSummer = false;
const fruits = {
    apple: 10,
    banana: 5,
    ...(isSummer && { watermelon: 30 }),
};

Reference: MDN

ppppppppppp

Syntax:



Example 1:



Example 2: HHHHHH


ppppppppppp

Syntax:



Example 1:



Example 2: HHHHHH


ppppppppppp

Syntax:



Example 1:



Example 2: HHHHHH


ppppppppppp

Syntax:



Example 1:



Example 2: HHHHHH


ppppppppppp

Syntax:



Example 1:



Example 2: HHHHHH


ppppppppppp

Syntax:



Example 1:



Example 2: HHHHHH


ppppppppppp

Syntax:



Example 1:



Example 2: HHHHHH


returns: Array

The split() method splits a string into an array of substrings. uses a seperator to make the split area.

Syntax:

const str = 'My name is Karthi, Iam an athlet';
console.log( str.split('a') )
//["My n", "me is K", "rthi, I", "m ", "n ", "thlet"]

console.log( str.split(' ') )
//["My", "name", "is", "Karthi,", "Iam", "an", "athlet"]

console.log( str.split() )
//['My name is Karthi, Iam an athlet']

Example 1:



Example 2: HHHHHH


ppppppppppp

Syntax:



Example 1:



Example 2: HHHHHH


JS Array methods in Pictorial

(for quick reference - from linkedin docs)