Some more Array Methods in JavaScript

 let num = [1, 2, 3, 4, 5, 6, 7, 8, 9];

let num_more = [11, 12, 13, 14, 15, 16, 17, 18, 19];
let num_even_more = [211, 212, 213, 214, 415, 416, 417, 418, 419];
console.log(num.length);
delete num[0];  //"delete" is a Operator(just like "typeof" operator), Not method
console.log(num.length);

let newArray = num.concat(num_more, num_even_more);
console.log(newArray);

let numTwo = [551, 22, 3, 14, 5, 6, 7, 8, 229];
numTwo.sort();  //sort() method is used to sort an array alphabetically
console.log(numTwo);

// sorting in Ascending Order
let compare = (a, b) => {
    return a - b;
}
numTwo.sort(compare);
console.log(numTwo);

// sorting in Descending Order
let compareTwo = (a, b) => {
    return b - a;
}
numTwo.sort(compareTwo);
console.log(numTwo);

let numThree = [551, 22, 3, 14, 5, 6, 7, 8, 229];
console.log(numThree.reverse());

//Splice and Slice
//Splice can be used to add new items to an array
let numFour = [551, 22, 3, 14, 5, 6, 7, 8, 229];
//Syntax: numFour.splice(position to add, No of elements to remove, Elements to be added);
numFour.splice(2, 3, 1021, 1022, 1023);
console.log(numFour);
//ArrayName.splice() returns deleted items and modifies the Array
let deletedValues = numFour.splice(2, 3, 1021, 1022, 1023);
console.log(deletedValues, typeof deletedValues);

//slice() : slices out a piece from an array. It creates a new Array
let numFive = [551, 22, 3, 14, 5, 6, 7, 8, 229];
let newNum = numFive.slice(3);
console.log(newNum);
let newNumTwo = numFive.slice(3, 6);    //Here Last "6th" index value will not include
console.log(newNumTwo);


OUTPUT :
9 9 [ <1 empty item>, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 211, 212, 213, 214, 415, 416, 417, 418, 419 ] [ 14, 22, 229, 3, 5, 551, 6, 7, 8 ] [ 3, 5, 6, 7, 8, 14, 22, 229, 551 ] [ 551, 229, 22, 14, 8, 7, 6, 5, 3 ] [ 229, 8, 7, 6, 5, 14, 3, 22, 551 ] [ 551, 22, 1021, 1022, 1023, 6, 7, 8, 229 ] [ 1021, 1022, 1023 ] object [ 14, 5, 6, 7, 8, 229 ] [ 14, 5, 6 ]

Comments

Popular posts from this blog

Generators tutorial in Advance JavaScript

Document Object Module DOM querySelector and querySelectorAll tutorial in JavaScript

Find Even and Odd Numbers with Loops tutorial in JavaScript