JS_Arrays in JS.docx
JS_Arrays in JS.docx
Properties:
Constructor
length - a number to denote the number of elements in an array.
let arr1=[1,2,3,[4,5] ] ; console.log(arr1.length) ; will print 4 .
slice () takes +ve and -ve values as arguments and also one or two arguments.
slice( +ve, +ve ) - denotes starting index, ending index
slice( +ve) - slice the elements from the specified index to the last.
slice(-ve) - slices the array from the position indexed from the last.
slice(+ve, -ve) - slices the array from the given position to the end position indexed from the last.
let scores=[10,20,21,25,26,28,39];
let sliced=scores.slice(2,4);
console.log(sliced);// output is [ 21, 25 ]
console.log(scores.slice(2));// output is [ 21, 25, 26, 28, 39 ]
console.log(scores.slice(-3));// output is [ 26, 28, 39 ]
console.log(scores.slice(2,-3));// output is [ 21, 25 ]
v) Sorting and reversing an array. // This is an mutate function which changes the calling
array object also.
scores=[3,5,3,2,6,8,4,2,1];
console.log(scores.sort()); //output is [ 1, 2, 2, 3, 3, 4, 5, 6, 8]
console.log(scores.reverse()); // output is [8, 6, 5, 4, 3, 3, 2, 2, 1 ]
In ES2023 toSorted and toReversed() methods return the sorted and reversed array to a new
array without altering the original array.
i) indexOf: returns the index position of the element occurring first time from the given index
position.
scores=[3,5,3,2,6,8,4,2,1];
console.log(scores.indexOf(2)); // output is 3 from the beginning.
console.log(scores.indexOf(2,4)); // output is 7. from 4th position 2
occurs at 7
console.log(scores.indexOf(20)); // output is -1 to indicate no occurrence
of 20
ii) lastIndexOf : returns the position of last occurrence of the given element.
scores=[3,5,3,2,6,8,4,2,1];
console.log(scores.lastIndexOf(2)); // output is 7
console.log(scores.lastIndexOf(5,4)); // output is 1. from 4th position 2
occurs at 3
console.log(scores.lastIndexOf(20)); // output is -1 to indicate no
occurrence of 20
b) findLast ( function, < optional arguments>) - returns the last element that passes the
test condition.
scores=[1,3,5,2,6,5,8,9];
console.log(scores.findLast(num=>num%2!==0) ); // ouput is 9
console.log(scores.findLast(num=>num%2==0) ); // output is 8
Similarly learn about findLastIndex() ???//returns the index of the last element that passses the
condition