Table of contents
- What is an Array?
- Ways of declaring array in JavaScript.
- Ways to access array elements
- All Array Methods!!
- 1. at()
- 2. concat()
- 3. copyWithin()
- 4. entries()
- 5. every()
- 6. fill()
- 7. filter()
- 8. find()
- 9. findIndex()
- 10. findLast()
- 11. findLastIndex()
- 12. flat()
- 13. flatMap()
- 14. forEach()
- 15. Array.from()
- 16. includes()
- 17. indexOf()
- 18. Array.isArray()
- 19. join()
- 20. keys()
- 21. lastIndexOf()
- 22. map()
- 23. Array.of()
- 24. pop()
- 25. push()
- 26. reduce()
- 27. reduceRight()
- 28. reverse()
- 29. shift()
- 30. slice()
- 31. some()
- 32. sort()
- 33. splice()
- 34. toLocaleString()
- 35. toString()
- 36. unshift()
- 37. values()
What is an Array?
- Array is an collection of elements of same datatype. But in JS Array is an collection of elements of multiple datatypes.
- in JS, Array is an Object. You can suppose index of an Array element as it's key and element itself as it's value, just like Object's key value pair.
- Array is a non primitive Datatype.
- First element is at 0th index.
- Array in JS, also support negative indexing.
Ways of declaring array in JavaScript.
Using Array Constructor.
- if you pass a number as an arguments to the constructor, it will create empty array of that size.
- But if you pass a string or more than one parameter it will treat them as the elements.
const arr1 = new Array(4);
console.log(arr1.length); // Output -> 4
console.log(arr1[0]); // Output -> undefined
const arr2 = new Array(4,5);
console.log(arr2.length); // Output -> 2
console.log(arr2[0]); // Output -> 4
const arr3 = new Array('Kartik');
console.log(arr3.length); // Output -> 1
console.log(arr3[0]); // Output -> Kartik
Using Array.of()
method
- Create an Array using
Array.of()
method of the Array class.
const arr = Array.of(20, 'Kartik', 3.14, false);
console.log(arr) // Output -> [ 20, 'Kartik', 3.14, false]
Using []
- Easiest way to create an Array is using
[]
square brackets
const arr = [10, 'Hitesh', 3.98, true];
console.log(arr) // Output -> [10, 'Hitesh', 3.98, true]
Ways to access array elements
Using []
square bracket notations.
const arr = [10, 'Hitesh', 3.98, true];
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
console.log(arr[3]);
// Output ->
// 10
// Hitesh
// 3.98
// true
Using at()
method
const arr = [10, 'Hitesh', 3.98, true];
console.log(arr.at(0));
console.log(arr.at(1));
console.log(arr.at(2));
console.log(arr.at(3));
// Output ->
// 10
// Hitesh
// 3.98
// true
All Array Methods!!
1. at()
- Syntax -
at(index)
- Using
at()
method you can fetch the element at a particular index by passing index number as a parameter. - It returns
undefined
if the element is not present at that specific index.
const arr = ['React', 'Angular', 'ExpressJS', 'MongoDB', 'Nodejs', 'NextJs'];
console.log(arr.at(1)); // Output -> Angular
console.log(arr.at(6)); // Output -> undefined
2. concat()
- Syntax -
concat(value0, value1, ....., valueN)
- It accepts n number of arrays as parameter(s).
- We can combine multiple arrays using
concat()
method. - It doesn't modify original array instead returns new array.
- If we don't provide any parameter to the method, it creates a shallow copy of the array.
- In the below example, we are combining 3 arrays.
const languages = ['JavaScript', 'Go'];
const styling = ['CSS', 'Tailwind'];
const frameworks = ['React', 'Angular'];
const concatedArray = languages.concat(styling, frameworks);
console.log('concatedArray ->' ,concatedArray);
// Output -> [ 'JavaScript', 'Go', 'CSS', 'Tailwind', 'React', 'Angular' ]
3. copyWithin()
- Syntax
copyWithin(target, start, end)
. It accepts three parameters.
target
(Optional) - the target index to where elements will be copied. Default is0
.start
(Optional) - the start index from where the elements will be copied. Default is0
.end
(Optional) - the end index till where elements will be copied. Default is0
It copies the elements from the array to a different location of the same array.
- It modifies the existing array but not the length of the array.
- Here, in below example we have to copy from start index 3 and end index 6(not inclusive) so the elements that we are copying are
C++, Java, Go
and will replace the elements starting from the targeted index 1 that arepython, C, C++
.
const languages = ['JavaScript', 'Python', 'C', 'C++', 'Java', 'Go', 'Swift'];
languages.copyWithin(1, 3, 6);
console.log('languages -> ',languages);
// Output -> ['Javascript', 'C++', 'Java', 'Go', 'Java', 'Go', 'Swift', 'Ruby']
4. entries()
- Syntax -
entries();
entries()
method creates a new Array Iterator Object.- It doesn't modifies the current array.
- It returns a new Array Iterator Object
- The output of this method is Array of multiple Arrays with each consist of 2 values i.e. one index and one element itself. You can see in the example below.
const languages = ['Javascript', 'Python', 'Go', 'Swift', 'Ruby'];
const iterator = languages.entries();
for(const element of iterator) {
console.log(element);
}
// Output ->
// [ 0, 'Javascript' ]
// [ 1, 'Python' ]
// [ 2, 'Go' ]
// [ 3, 'Swift' ]
// [ 4 'Ruby' ]
5. every()
- Syntax -
every((element, index, array) => { /* … */ } )
every()
accepts a arrow function as a parameterarrow function
- It executes for each element of the array. It also accepts 3 parameterelement
- element of that particular iterationindex
- index of the element.array
- the array itself.
- It returns true when a specific condition is true for all the elements in the array else returns false.
- Below example explains how every method on first array returns
true
as all the elements satisfies the condition of type string whereas the second array returnsfalse
.
const languages = ['Javascript', 'Python', 'C', 'C++', 'Java', 'Go'];
let isStringArray = languages.every((element) => {
return typeof element == 'string' ? true : false
});
console.log(isStringArray); // Output -> true
const randomArray = ['this', 'is', 'a', 'random', 'array', 100];
isStringArray = randomArray.every((element) => {
return typeof element == 'string' ? true : false
});
console.log(isStringArray); // Output -> false
6. fill()
- Syntax -
fill(value, start, end)
- It accepts three parameter
value
- value that we have to fill from start to end Index.start
(Optional) - starting index from where value will be filled in the array. Default is0
.end
(Optional) - end index till where value will be filled in the array. end index is not inclusive in the range. Default isarray.length
.
- Replaces the elements of the array by the
value
depending on thestart
andend
index we provide to the method. - Default
start
value is 0 andend
value is array.length. - It returns the modified array that is filled with
value
. - In the Below Example, value is
Java
, Start is 1 and end is 3. So the element on index 1,2 are replaced or we can say filled by the value.
const languages = ['Javascript', 'Python', 'Go', 'Swift', 'Ruby'];
languages.fill('Java', 1, 3);
console.log(languages);
// Output -> [ 'Javascript', 'Java', 'Java', 'Swift', 'Ruby' ]
7. filter()
- Syntax -
filter((element, index, array) => { /* … */ } )
filter()
accepts a arrow function as a parameterarrow function
- It executes for each element of the array. It also accepts 3 parameterelement
- element of that particular iterationindex
- index of the element.array
- the array itself.
It filters the elements based on a the condition from the array and, creates and returns a shallow copy of elements of an array that passes the condition provided inside arrow function.
- It doesn't modify the original array.
- In the below example we are filtering the elements which are greater than or equal to 100.
const numbers = [10, 100, 45, 3000, 225, 2];
const numbersgt100 = numbers.filter((element) => {
return element >= 100 ? true : false
});
console.log(numbersgt100); // Output -> [ 100, 3000, 225 ]
8. find()
- Syntax
find((element, index, array) => { /* … */ } )
. find()
accepts a arrow function as a parameterarrow function
- It executes for each element of the array. It also accepts 3 parameterelement
- element of that particular iterationindex
- index of the element.array
- the array itself.
- It finds and returns the first element from array which satisfies the condition inside the arrow.
- In below example, we find the first element that starts with 'H' and i.e. Hitesh.
const names = ['Kartik', 'Hitesh', 'Harsh', 'Anirudh'];
const result = names.find((element) => {
return element.startsWith('H') ? true : false
});
console.log(result); // Output -> Hitesh
9. findIndex()
- Syntax
findIndex((element, index, array) => { /* … */ } )
. findIndex()
accepts a arrow function as a parameterarrow function
- It executes for each element of the array. It also accepts 3 parameterelement
- element of that particular iterationindex
- index of the element.array
- the array itself.
- It finds and returns the index of first element from array which satisfies the arrow condition.
- It's just like
find()
method but instead of element it returns the index of the element. - In below example, we find the first element that starts with 'H' i.e Hitesh and it's index is 1.
const names = ['Kartik', 'Hitesh', 'Harsh', 'Anirudh'];
const result = names.findIndex((element) => {
return element.startsWith('H') ? true : false
});
console.log(result); // Output -> 1
10. findLast()
- Syntax
findLast((element, index, array) => { /* … */ } )
. findLast()
accepts a arrow function as a parameterarrow function
- It executes for each element of the array. It also accepts 3 parameterelement
- element of that particular iterationindex
- index of the element.array
- the array itself.
- It finds and returns the last element from array which satisfies the arrow condition.
- It is opposite of
find()
method asfind()
method returns the first element. - While writing this article, node.js doesn't support this method. Maybe in future it might come.
- In below example, we find the last element that starts with 'H'.
const names = ['Kartik', 'Hitesh', 'Harsh', 'Anirudh'];
const result = names.findLast((element) => {
return element.startsWith('H') ? true : false
});
console.log(result);// Output -> Harsh
11. findLastIndex()
- Syntax
findLadtIndex((element, index, array) => { /* … */ } )
. findLastIndex()
accepts a arrow function as a parameterarrow function
- It executes for each element of the array. It also accepts 3 parameterelement
- element of that particular iterationindex
- index of the element.array
- the array itself.
- It finds and returns the index of last element from array which satisfies the arrow condition.
- It's just like
findLast()
method but instead of element it returns the index of the element. - It is opposite of
findIndex()
method asfindIndex()
method returns the index of first element. - In below example, we find the last element that starts with 'H' i.e Harsh and it's index is 2.
const names = ['Kartik', 'Hitesh', 'Harsh', 'Anirudh'];
const result = names.findLastIndex((element) => {
return element.startsWith('H') ? true : false
});
console.log(result); // Output -> 2
12. flat()
- Syntax -
flat(depth)
flat()
accepts one parameter.depth
(Optional) - the level of flattening of array. Defaultdepth
value is 1.
flat()
method flattens the nested arrays in an array depending upon thedepth
we specify. If we want to flatten the nested arrays at maximum level possible than we can provideInfinity
as adepth
parameter.- It does not modifies the existing array instead returns the new flattened array.
- In the below example we are first flattening the array at the
depth
of1
and in the second result we are flattening at the maximum level i.e.Infinity
possible so it flattens all the elements.
const names = [['Kartik'], [['Hitesh', 'Harsh']] , [[['Anirudh', 'Akash']]] ];
const result1 = names.flat(1);
console.log(result1);
// Output -> [ 'Kartik', [ 'Hitesh', 'Harsh' ], [ [ 'Anirudh', 'Akash' ] ] ]
const result2 = names.flat(Infinity);
console.log(result2);
// Output -> [ 'Kartik', 'Hitesh', 'Harsh', 'Anirudh', 'Akash' ]
13. flatMap()
- Syntax
flatMap((element, index, array) => { /* … */ } )
. flatMap()
accepts a arrow function as a parameterarrow function
- It executes for each element of the array. It also accepts 3 parameterelement
- element of that particular iterationindex
- index of the element.array
- the array itself.
flatMap()
method is a combination ofmap()
andflat()
method.- It does not modifies the existing array instead returns the new flattened and mapped array.
- First it map the elements and then flattens the resulted map by the
depth
of 1. - In below example we are comparing the result of
map()
andflatmap()
method. You can see the result ofmap()
method contains nested arrays when we apply split method to each element of the array, but the result of theflatMap()
is a flattened array.
const names = ['Kartik Gupta', 'Hitesh Chaudhary', 'Anurag Tiwari'];
const mapResult = names.map(e => e.split(' '));
console.log(mapResult);
// Output -> [[ 'Kartik', 'Gupta' ], [ 'Hitesh', 'Chaudhary' ], [ 'Anurag', 'Tiwari' ]]
const flatMapResult = names.flatMap(e => e.split(' '));
console.log(flatMapResult);
// Output -> [ 'Kartik', 'Gupta', 'Hitesh', 'Chaudhary', 'Anurag', 'Tiwari' ]
14. forEach()
- Syntax
forEach((element, index, array) => { /* … */ } )
. forEach()
accepts a arrow function as a parameterarrow function
- It executes for each element of the array. It also accepts 3 parameterelement
- element of that particular iterationindex
- index of the element.array
- the array itself.
forEach()
works just likefor
loop but it is a method not a loop. It executes the specified function for all the elements of the array.- It neither modifies the existing array nor creates a new array.
- In below example, we iterated over a
numbers
array usingforEach()
and then pushes square of each element ofnumbers
array to thesquareNumbers
array.
const numbers = [1,2,3,4,5,6];
const squareNumbers = [];
numbers.forEach((element)=>{
squareNumbers.push(element**2)
});
console.log(squareNumbers); // Output -> [ 1, 4, 9, 16, 25, 36 ]
15. Array.from()
- Syntax -
Array.from(arrayLike, (element, index) => { /* … */ } )
Array.from()
accepts a two parameterarrayLike
- instance of arraylike iterable and a arrow functionarrow function
- It executes for each element of the array. It also accepts 3 parameterelement
- element of that particular iterationindex
- index of the element.array
- the array itself.
Array.from()
is a static method of Array class.Array.from
creates a array from a iterable or array-like object like and will also perform the arrow function for each element of the iterable.- In the below example, I have passed 'Kartik' (String) as a array-like iterable and for every character it performs
toUpperCase()
to capitalize each character and stored it in an array as separate element.
const myName = Array.from('Kartik', (element => {
return element.toUpperCase();
}));
console.log(myName); // Output -> [ 'K', 'A', 'R', 'T', 'I', 'K' ]
16. includes()
- Syntax
includes(searchElement, fromIndex)
includes()
method accepts two parameters.searchElement
- Element which we want to check whether it is included in the array or not -fromIndex
(Optional) - starting index from where we want to check thesearchElement
. Default is0
includes()
method returnstrue
if the element is included in the array else it returnsfalse
.- In the below example, we are checking whether the array includes the name 'Hitesh' or not.
const names = ['Kartik', 'Hitesh', 'Anurag', 'Anirudh', 'Akash'];
console.log(names.includes('Hitesh')); // Output -> true
console.log(names.includes('Hitesh', 2)); // Output -> false
17. indexOf()
- Syntax
indexOf(searchElement, fromIndex)
indexOf()
method accepts two parameters.searchElement
- Element which we want to check in the arrayfromIndex
(Optional) - starting index from where we want to check thesearchElement
. Default is0
indexOf()
method returns the first index of thesearchElement
if the element is present in the array else it returns -1.- In the below example we are checking what is first the index of 'Hitesh'.
const names = ['Kartik', 'Hitesh', 'Anurag', 'Anirudh', 'Akash'];
console.log(names.indexOf('Hitesh')); // Output -> 1
console.log(names.indexOf('Hitesh', 2)); // Output -> -1
18. Array.isArray()
- Syntax
Array.isArray(value)
Array.isArray()
takesvalue
as a parameter and check whether thevalue
is an array or not.Array.isArray()
is a static method of Array class.Array.isArray()
returns true if thevalue
is an array else it returns false.- In below example, we are checking if the provided
value
is an Array or not.
const anArray = [1,2,3,4];
console.log(Array.isArray(anArray)); // Output -> true
const notAnArray = 1234;
console.log(Array.isArray(notAnArray)); // Output -> false
19. join()
- Syntax
join(separator)
join()
accepts one parameterseparator
- used for separating array elements after joining in a string.
join()
methods joins all the elements of the array and creates a string in which elements are separated using theseparator
parameter.- In the below Example, we are joining all the elements of the array as String separated by
,
const webStack = ['Javascript', 'HTML', 'CSS'];
console.log(webStack.join(', ')); // Output-> Javascript, HTML, CSS
20. keys()
- Syntax
keys()
keys()
method returns a new Array Iterator object that contains the keys for each index in the array.keys()
method is mostly used with objects and in JS Array is also an object, so Array inherit thekeys()
method from its parent class and that is Object.- Refer below example.
const anArray = ['Kartik', 'Hitesh', 'Anurag', 'Anirudh'];
const keys = anArray.keys();
for(let key of keys) {
console.log(key);
}
// Output ->
// 0
// 1
// 2
// 3
21. lastIndexOf()
- Syntax
lastIndexOf(searchElement, fromIndex)
lastIndexOf()
method accepts two parameters.searchElement
- Element which we want to check in the arrayfromIndex
(Optional) - starting index from where we want to check thesearchElement
. Default is0
lastIndexOf()
method returns the last index of thesearchElement
if the element is present in the array else it returns -1.lastIndexOf()
method doesn't ignore the elements at indexes beforefromIndex
. It just wrap around and iterate from 0 tofromIndex
-1 after reaching the end of the array.- In the below example we are checking what is the last index of 'Kartik'.
const names = ['Kartik', 'Hitesh', 'Kartik', 'Anirudh', 'Akash'];
console.log(names.lastIndexOf('Kartik')); // Output -> 2
console.log(names.lastIndexOf('Kartik', 1)); // Output -> 0
22. map()
- Syntax
map((element, index, array) => { /* … */ })
map()
accepts a arrow function as a parameterarrow function
- It executes for each element of the array. It also accepts 3 parameterelement
- element of that particular iterationindex
- index of the element.array
- the array itself.
map()
method creates a new array which is populated based on the condition applied on the each element of the array.- It doesn't modifies the original array but instead return a new array.
- In below example we are appending the index of the element to the element itself using
map()
.
const names = ['Kartik', 'Hitesh', 'Anurag', 'Hitesh', 'Akash'];
const newNames = names.map((element, index) => {
return element +' ' + index;
});
console.log(newNames);
// Output -> [ 'Kartik 0', 'Hitesh 1', 'Anurag 2', 'Hitesh 3', 'Akash 4' ]
23. Array.of()
- Syntax
Array.of(element0, element1, /* … ,*/ elementN)
Array.from()
is a static method of Array class.- It accepts n numbers of elements and creates a array out of it.
- In the below example we have passed 3 arguments/parameter to the method and as a result we got a array of length 3.
const anArray = Array.of('JavaScript', 'HTML', 'CSS');
console.log(anArray); // Output -> ['JavaScript', 'HTML', 'CSS']
24. pop()
- Syntax
pop()
pop()
method removes the last element from the array.- It returns that element that is poped out or removed from the end.
- It modifies the original array.
- In below example we are applying
pop()
to thenumbers
array.
const numbers = [9, 20, 34, 53, 71, 29, 45];
console.log(numbers.pop());
// Output -> 45
console.log(numbers.length);
// Output -> 6
console.log(numbers);
// Output -> [9, 20, 34, 53, 71, 29]
25. push()
- Syntax
push(element0, element1, /* … ,*/ elementN)
- It adds n numbers of elements provided in parameters at the end of the array
- It returns the length of the array.
- It modifies the original array.
const numbers = [9, 20, 34, 53, 71, 29, 45];
console.log(numbers.push(50));
// Output -> 8
console.log(numbers);
// Output -> [9, 20, 34, 53, 71, 29, 45, 50]
console.log(numbers.push(29, 68));
// Output -> 10
console.log(numbers);
// Output -> [9, 20, 34, 53, 71, 29, 45, 50, 29, 68]
26. reduce()
- Syntax
reduce((previousValue, currentValue, currentIndex, array) => { /* … */ }, initialValue)
reduce()
method accepts aarrow function
and ainitialValue
as a parameterarrow function
can accept 4 parameters.previousValue
- the result of the previous operationcurrentValue
- current element of the arraycurrentIndex
- index of the elementarray
- the array itself
initialValue
(Optional) - value ofpreviousValue
parameter in the callback for the first iteration.
- For the first iteration,
-If
initialValue
is specified thanprevioudValue
is equal to theinitialValue
andcurrentValue
is equal to the first element of the array.- If
initialValue
is not specified thanprevioudValue
is equal to the first element and first element is skipped from the iteration of the array andcurrentValue
is equal to the second element of the array.
- If
reduce()
method executes arrow function on every element of the array and results into a single value.- In below example, we are applying reduce method on the array to generate a reduced string.
const factArr = ['Honesty', 'is', 'the', 'best', 'policy'];
const universalTruth = factArr.reduce((pv, cv) => {
return pv + ' ' + cv;
},'');
console.log(universalTruth);
// Output -> Honesty is the best policy
27. reduceRight()
- Syntax
reduceRight((accumulator, currentValue, index, array) => { /* … */ }, initialValue)
reduceRight()
is same asreduce()
. The only difference is the direction of iteration.reduce()
iterate from left to right whereasreduceRight()
iterates from right to left. Please refer toreduce()
method first before understandingreduceRight()
.reduceRight()
method accepts aarrow function
and ainitialValue
as a parameterarrow function
can accept 4 parameters.accumulator
- the result of the previous operationcurrentValue
- current element of the arraycurrentIndex
- index of the elementarray
- the array itself
initialValue
(Optional) - value ofaccumulator
parameter in the callback for the first iteration.
- For the first iteration,
-If
initialValue
is specified thanaccumulator
is equal to theinitialValue
andcurrentValue
is equal to the last element of the array.- If
initialValue
is not specified thanaccumulator
is equal to the last element and last element is skipped from the iteration of the array andcurrentValue
is equal to the last second element of the array.
- If
reduceRight()
method executes arrow function on every element of the array and results into a single value.- In below example, we are applying reduce method on the array to generate a reduced string.
const factArr = ['Honesty', 'is', 'the', 'best', 'policy'];
const universalTruth = factArr.reduce((pv, cv) => {
return pv + ' ' + cv;
},'');
console.log(universalTruth);
// Output -> ploicy best the is Honesty.
28. reverse()
- Syntax
reverse()
reverse()
method reverses the array.- It modifies the original array and returns the reversed array.
- check the below example.
const names = ['Kartik', 'Hitesh', 'Anurag', 'Anirudh', 'Akash'];
console.log(names.reverse())
// Output -> ['Akash', 'Anirudh', 'Anurag', 'Hitesh', 'Kartik']
29. shift()
- Syntax
shift()
shift()
method removes the first element from the array.- It returns the element that is removed.
- It modifies the original array.
- In below example we are applying
shift()
to thenumbers
array.
const numbers = [9, 20, 34, 53, 71, 29, 45];
console.log(numbers.shift());
// Output -> 9
console.log(numbers.length);
// Output -> 6
console.log(numbers);
// Output -> [ 20, 34, 53, 71, 29, 45 ]
30. slice()
- Syntax
slice(start, end)
slice()
accepts two parameters.start
(Optional) - Start Index. Default is0
.end
(Optional) - End Index (not inclusive). Default isarray.length
.
- It doesn't modifies the original array.
- It slices out a specific portion of array based on start and end Index values.
- It returns the sliced array.
- Refer to below example.
const names = ['Kartik', 'Hitesh', 'Anurag', 'Anirudh', 'Akash'];
console.log(names.slice(1,3));
// Output -> ['Hitesh', 'Anurag']
31. some()
- Syntax
some((element, index, array) => { /* … */ } )
some()
accepts a arrow function as a parameterarrow function
- It executes for each element of the array. It also accepts 3 parameterelement
- element of that particular iterationindex
- index of the element.array
- the array itself.
- It returns
true
when a specific condition is satsifies for at least one element in the array else returnsfalse
. - Below example explains even if one element satisfies the condition then the result is
true
.
const randomArray = ['this', 'is', 'a', 'random', 'array', 100];
let isNumberArray = randomArray.some((element) => {
return typeof element == 'number' ? true : false
});
console.log(isNumberArray); // Output -> true
const languages = ['Javascript', 'Python', 'C', 'C++', 'Java', 'Go'];
isNumberArray = languages.some((element) => {
return typeof element == 'number' ? true : false
});
console.log(isNumberArray); // Output -> false
32. sort()
- Syntax
sort((a, b) => { /* … */ } )
- It accepts a arrow function
arrow function
(Optional) - It executes logic of comparisions of two elements. It also accepts 2 parameter.a
- First element for comparision.b
- Second element for comparision.
sort()
is used to sort the array based on the comparision arrow function.- If arrow function is not specified than it will sort based the elements based on the string comparision.
- if the sorting arrow function returns value less than
0
thana
will come beforeb
and vice versa. - If the sorting arrow function return
0
, it will keep the a and b at original place. - In below example we are sorting elements in decending order.
const numbers = [9, 20, 34, 53, 71, 29, 45];
numbers.sort((a,b) => {
return a > b ? -1 : 1;
});
console.log(numbers);
// Output -> [71, 53, 45, 34, 29, 20, 9]
33. splice()
- Syntax
splice(start, deleteCount, item1, item2, ... itemN)
splice()
accepts multiple paramters.start
- index at which to start changing the array.deleteCount
- How many elements to delete fromstart
item1, item2, ... itemN
- number of items to replace with the deleted elements.
- It deletes the elements from
start
index tostart + deleteCount
Index and will replace with the n items passed to the method. - It returns the array of deleted elements.
- It also changes the length of the array.
- It modifies the original array by replacing the deleted elements by the other passed items.
- If deletedCount is
0
then no elements would be deleted and items will be added to the start index pushing the later elements forward in the array resulting in increasing the length of the array. - If no items are passed to the method than the elements will be deleted from
start
index tostart + deletedCount
index resulting in decreasing the length of the array. - In the below example, we deleting replacing
"Anurag", "Anirudh"
and replacing them by"Ajinkya", "Mandeep", "Shubham"
.
const names = ['Kartik', 'Hitesh', 'Anurag', 'Anirudh', 'Akash'];
console.log(names.splice(2, 2, "Ajinkya", "Mandeep", "Shubham"));
// Output -> [ 'Anurag', 'Anirudh' ]
console.log(names);
// Output -> ['Kartik', 'Hitesh', 'Ajinkya', 'Mandeep', 'Shubham', 'Akash']
34. toLocaleString()
- Syntax
toLocaleString(locales, options);
toLocalString()
accepts two parameters.locales
- specific language format to useoptions
- object to set properties like timezone
- It is mostly used with Date and Time, Numbers or Objects sometimes. Very rarely used with Arrays.
- The toLocaleString() method returns a string representing the elements of the array.
- The elements are converted to Strings using their toLocaleString methods and these Strings are separated by a locale-specific String (such as a comma ",").
const array1 = [1, 'a', new Date('28 Aug 2022 18:35:00 UTC')];
const localeString = array1.toLocaleString('hi-IN', { timeZone: 'IST' });
console.log(localeString);
// Output -> 1,a,29/8/2022, 12:05:00 am
35. toString()
- Syntax
toString()
- It joins all the elements of arrays seperated by commas(-).
- It returns the string of elements seperated by commas and it doesn't modifies the original array.
- Refer below example.
const numbers = [9, 20, 34, 53, 71, 29, 45];
console.log(numbers.toString());
// Output -> 9,20,34,53,71,29,45
console.log(numbers);
// Output -> [9, 20, 34, 53, 71, 29, 45]
36. unshift()
- Syntax
unshift(element0, element1, /* … ,*/ elementN)
- It adds n numbers of elements provided in parameter to the start of the array.
- It returns the length of the array.
- It modifies the original array.
const numbers = [9, 20, 34, 53, 71, 29, 45];
console.log(numbers.unshift(50));
// Output -> 8
console.log(numbers);
// Output -> [50, 9, 20, 34, 53, 71, 29, 45]
console.log(numbers.unshift(29, 68));
// Output -> 10
console.log(numbers);
// Output -> [29, 68, 50, 9, 20, 34, 53, 71, 29, 45]
37. values()
- Syntax
values()
values()
method returns a new array iterator object that contains the values for each index in the array.values()
method is mostly used with objects and in JS Array is also an object, so Array inherit thevalues()
method from its parent class and that is Object.- Refer Below Example
const anArray = ['Kartik', 'Hitesh', 'Anurag', 'Anirudh'];
const values = anArray.values();
for(let value of values) {
console.log(value);
}
// Output ->
// 'Kartik'
// 'Hitesh'
// 'Anurag'
// 'Anirudh'