📄 Table of Contents

◉ How an array in JS is different from array in other languages

var House = [ ];         // method 1 (preferred method)
var House = new array(); // method 2
// Initializing while declaring
var house = new Array(10, 20, 30, 40, 50);
# Creates an array having elements 10, 20, 30, 40, 50


var house1 = new Array(5);
# Creates an array of 5 undefined elements

◉ Check if variable is an Array in JavaScript?

Array.isArray(variableName)
Array.isArray([1, 2, 3]);  // true
Array.isArray({foo: 123}); // false
Array.isArray('foobar'); // false
Array.isArray(undefined); // false
variable instanceof Array
let arr = [1, 2, 3];
alert( arr instanceof Array ); // true
alert( arr instanceof Object ); // true

👉 instanceof vs isArray()

variable.constructor === Array
let str = [1,2,3,4,5];str.constructor === Array;  # true
str.constructor === Object; # false

◉ Basic Array Sorting

const foo = [99, 11, 41, 'zzz', 'aaa'];
foo.sort(); // returns [ 11, 41, 99, 'aaa', 'zzz' ]
const bar = [5, 18, 32, new Set, { user: 'anil kumar' }];
bar.sort(); // returns [ 18, 32, 5, { user: 'anil kumar' }, Set {} ]
const foo = ['I love javascript', 37, 9, 5, 17];
foo.sort(); // foo array is modified
console.log(foo); // shows [ 17, 37, 5, 9, 'I love javascript' ]
const sortedFoo = foo.slice().sort(); // a new instance of the foo array is created and sorted
const sortedFoo = [...foo].sort(); 
// a new instance of the foo array is created and sorted
console.log(foo);        // ['I love javascript', 37, 9, 5, 17];
console.log(sortedFoo); // [ 17, 37, 5, 9, 'I love javascript' ]

Using Compare Functions to Sort

const nums = [79, 48, 12, 4];function compare(a, b) {
if (a > b) return 1;
if (b > a) return -1;
return 0;
}
nums.sort(compare);
// => 4, 12, 48, 79
function compare(a, b) {
return a - b;
}
nums.sort((a, b) => a - b);

How to Sort an Array of Objects in JavaScript

const singers = [
{ name: 'Steven Tyler', band: 'Aerosmith', born: 1948 },
{ name: 'Karen Carpenter', band: 'The Carpenters', born: 1950 },
{ name: 'Kurt Cobain', band: 'Nirvana', born: 1967 },
{ name: 'Stevie Nicks', band: 'Fleetwood Mac', born: 1948 },
];
function compare(a, b) {
// Use toUpperCase() to ignore character casing
const bandA = a.band.toUpperCase();
const bandB = b.band.toUpperCase();
let comparison = 0; if (bandA > bandB) {
comparison = 1;
} else if (bandA < bandB) {
comparison = -1;
}
return comparison;
}
singers.sort(compare);/* returns [
{ name: 'Steven Tyler', band: 'Aerosmith', born: 1948 },
{ name: 'Stevie Nicks', band: 'Fleetwood Mac', born: 1948 },
{ name: 'Kurt Cobain', band: 'Nirvana', born: 1967 },
{ name: 'Karen Carpenter', band: 'The Carpenters', born: 1950 }
] */
function compare(a, b) {
...
//invert return value by multiplying by -1
return comparison * -1;
}

Creating a Dynamic Sorting Function

const singers = [
{ name: 'Steven Tyler', band: 'Aerosmith', born: 1948 },
{ name: 'Karen Carpenter', band: 'The Carpenters', born: 1950 },
{ name: 'Kurt Cobain', band: 'Nirvana', born: 1967 },
{ name: 'Stevie Nicks', band: 'Fleetwood Mac', born: 1948 },
];
function compareValues(key, order = 'asc') {
return function innerSort(a, b) {
if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
// property doesn't exist on either object
return 0;
}
const varA = (typeof a[key] === 'string')
? a[key].toUpperCase() : a[key];
const varB = (typeof b[key] === 'string')
? b[key].toUpperCase() : b[key];
let comparison = 0;
if (varA > varB) {
comparison = 1;
} else if (varA < varB) {
comparison = -1;
}
return (
(order === 'desc') ? (comparison * -1) : comparison
);
};
}
// array is sorted by band, in ascending order by default
singers.sort(compareValues('band'));
// array is sorted by band in descending order
singers.sort(compareValues('band', 'desc'));
// array is sorted by name in ascending order
singers.sort(compareValues('name'));
// array is sorted by date if birth in descending order
singers.sort(compareValues('born', 'desc'));

String.prototype.localeCompare()

['bjork', 'Bjork', 'Björk'].sort();
// [ 'Bjork', 'Björk', 'bjork' ]
['bjork', 'Bjork', 'Björk'].sort((a, b) => a.localeCompare(b));
// [ 'bjork', 'Bjork', 'Björk' ]
function compareValues(key, order = 'asc') {
return function innerSort(a, b) {
if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) return 0;
const comparison = a[key].localeCompare(b[key]);
return (
(order === 'desc') ? (comparison * -1) : comparison
);
};
}

◉ New features of JavaScript Arrays with ES2015

[1]. Array De-structuring

let animals =['Dog','Cat','Rat'];let a = animals[0];
let b = animals[1];
let c = animals[2];
console.log(a,b,c);
let animals =['Dog','Cat','Rat'];
let [a,b,c] = animals;
console.log(a,b,c);
[a, ,b] = animals;
console.log(a,b); # Dog, Rat

[2]. iteration (for…of)

Enumerables vs Iterables

for…in vs for…of

Using ‘for…in’

let person = {
"first_name": "Jonathan",
"last_name": "Hsu",
"medium-handle": "@jhsu98"
}
for(const key in person) {
console.log(key + ": " + person[key]);
}
/*
"first_name: Jonathan"
"last_name: Hsu"
"medium-handle: @jhsu98"
*/

Using ‘for…of’

let scores = [43,58,28,69,38];for(const item of scores) {
console.log(item);
}
/*
43
58
28
69
38
*/
let person = {
"first_name": "Jonathan",
"last_name": "Hsu",
"medium-handle": "@jhsu98"
}
for(const item of person) {
console.log(item);
}
/*
"TypeError: person is not iterable
at gewuhimaza.js:6:84
at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:13924
at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:10866"
*/

I Thought Arrays Were Enumerables Too

let scores = [43,58,28,69,38];for(const item in scores) {
console.log(item);
}
/*
"0"
"1"
"2"
"3"
"4"
*/

[3]. Array.prototype.find()

let animals  = ['Dog', 'Cat', 'Rat'];let animal = animals.find(function(animal){
if(animal === 'Rat'){
return true;
}
});
console.log(animal); //Rat

[4]. Set

var set1 = new Set(["sumit","sumit","amit","anil","anish"]);
["sumit","amit","anil","anish"]
var set2 = new Set("fooooooood");
// 'f', 'o', 'd'
var set3 = new Set([10, 20, 30, 30, 40, 40]);
[10, 20, 30, 40]
// it is an empty set
var set4 = new Set();

[4]. Map (and not HOF map())

var map1 = new Map([[1 , 2], [2 ,3 ] ,[4, 5]]);
console.log("Map1");
// 1 => 2
// 2 => 3
// 4 -> 5
var map2 = new Map([["firstname" ,"sumit"],["lastname", "ghosh"], ["website", "geeksforgeeks"]]);
console.log("Map2");
// firstname => sumit
// lastname => ghosh
// website => geeksforgeeks

◉ Weirdness of Arrays in JS (from techsith)

const arr = [1,2,3];
const arr[-1]= 4;
console.log(arr); #(3) [1, 2, 3, -1: 4]
console.log(length); # 3
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~var arr1 = [];
arr1["index1"]= "anil";
arr1["index2"]= "kumar";
console.log(arr1); # [index1: "anil", index2: "kumar"]
console.log(arr1.length); # 0;

◉ Convert an Array to Object in JS:

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.