The Array object, enables storing a collection of multiple items under a single variable name. And has members for performing common array operations.
Adds element at the end of array. And returns the new length of the array.
push()
push(element1)
push(element1, element2, /* …, */ elementN)
const sports = ["soccer", "baseball"];
const total = sports.push("football", "swimming");
console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
console.log(total); // 4
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.
unshift()
unshift(element1)
unshift(element1, element2, /* …, */ 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]
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
pop()
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
shift()
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"]
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
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1, item2, /* …, */ itemN)
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']
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)
sort()
sort(compareFn)
const fruits = ['Orange', 'Pomogranate', 'Guava', 'Apple'];
fruits.sort();
console.log(fruits); // ['Apple', 'Guava', 'Orange', 'Pomogranate']
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]
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}
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;
}
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;
});
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(){return 0.5 - Math.random()});
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);
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:
(...)
const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];
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}
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]
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
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.
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]);
const dateFields = [1970, 0, 1]; // 1 Jan 1970
const da = new Date(...dateFields);
//Thu Jan 01 1970 00:00:00 GMT+0530 (IST)
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']
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 }
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
ppppppppppp
ppppppppppp
ppppppppppp
ppppppppppp
ppppppppppp
ppppppppppp
returns: Array
The split() method splits a string into an array of substrings. uses a seperator to make the split area.
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']
ppppppppppp
(for quick reference - from linkedin docs)