Diving Deeper into JavaScript Arrays: Unleashing Their Power and Flexibility
Before diving into the intricacies of JavaScript arrays, let's establish a solid foundation by understanding what arrays are and how they work.
What is a JavaScript Array β
At its core, an array is a data structure that allows you to store multiple values in a single variable. These values can be of any data type, including strings, numbers, objects, or even other arrays. Arrays in JavaScript are ordered, meaning each element has a specific index, starting from 0 for the first element, and they maintain the order in which elements were added.
Types of Indexing in Array π
0 (Zero-Based Indexing)- The first element of the array refers to index 0.
1 (One-Based Indexing)- The first element of the array refers to index 1.
n (n Based Indexing)- The base index of an array can be chosen as per requirement.
Creating an Array β»οΈ
JavaScript provides multiple ways to create arrays. The two most common methods are using array literals and the array constructor.
Using array literals :
// Using array literals const fruits = ['apple', 'banana', 'cherry'];
Using the array constructor :
// Using the array constructor const numbers = new Array(1, 2, 3, 4, 5);
Accessing Array Elements π
Accessing array elements is straightforward. You simply use the index of the element you want to retrieve.
// Using array literals
const fruits = ['apple', 'banana', 'cherry'];
const firstFruit = fruits[0]; // Retrieves 'apple'
console.log(firstFruit)
Is there any negative index in JavaScript β
No, JavaScript does not support negative indices for arrays. Array indices in JavaScript are always non-negative integers, starting from 0 for the first element.
If you attempt to access an array element using a negative index or an index that is not a valid integer, JavaScript will not throw an error but will return undefined
because there is no element at that index.
const myArray = [10, 20, 30];
console.log(myArray[-1]); // Returns undefined, no negative indices.
console.log(myArray[1.5]); // Returns undefined, non-integer index.
Array Methods π₯
Access the Full Array.
const cars2 = ["Saab", "Volvo", "BMW"]; console.log(cars2) console.log(typeof(cars2)) // object
You can see the type of array is an object right so this is because, Arrays in JavaScript are objects because of the language's dynamic typing, prototype-based inheritance, and object-centric design, allowing for flexibility and versatile data manipulation.
Update an Array Element.
const cars = ["Saab", "Volvo", "BMW"]; cars[0] = "Opel"; console.log(cars) //[ 'Opel', 'Volvo', 'BMW' ]
push():
push(
) method adds one or more elements to the end of an array and returns the new length of the array.console.log("...........................push()............") const animals1 = ['pigs', 'goats', 'sheep']; const count = animals1.push('cows'); console.log(count) //4 console.log(animals1) //[ 'pigs', 'goats', 'sheep', 'cows' ]
pop:
pop()
method removes the last element from an array and returns that element. This method changes the length of the array.console.log("................pop()..................") const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato']; console.log(plants.pop()); //tomato console.log( plants) // [ 'broccoli', 'cauliflower', 'cabbage', 'kale' ] // pop() will not take any aruguments if you give even it //goining to delete the last index only.
shift():
shift()
method removes the first element from an array and returns that removed element. This method changes the length of the array.console.log("..................shift().................") user=["Assam","Rajasthan"] user.shift() console.log(user) // [ 'Rajasthan' ]
unshift():
unshift()
method adds one or more elements to the beginning of an array and returns the new length of the array.console.log("......................unshift................") user1=["Assam","Rajasthan"] user1.unshift("Hello","kushal") console.log(user1) //[ 'Hello', 'kushal', 'Assam', 'Rajasthan' ]
concat():
concat()
method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.console.log(".........concat() method in JS...............") const array1 = ['a', 'b', 'c']; const array2 = [12,23.67,true]; const array3 = ["k","p"]; const final_array = array1.concat(array2,array3); console.log(final_array); //[ 'a','b','c',12,23.67,true,'k', 'p']
copyWithin():
copyWithin()
method shallow copies part of an array to another location in the same array and returns it without modifying its length.console.log(".........copyWithin() in js....................") const arr1 = ['a', 'b', 'c', 'd', 'e']; // copy to index 1 , all elements from index 3 to the end. let res=arr1.copyWithin(1, 3); console.log(res) // [ 'a', 'd', 'e', 'd', 'e' ] // It will change the original array permanently . const arr2 = ['a', 'b', 'c', 'd', 'e']; // copy to index 0 the element at index 3 console.log(arr2.copyWithin(0, 3, 4)); //[ 'd', 'b', 'c', 'd', 'e' ]
The
copyWithin()
method in JavaScript allows you to copy elements within an array. In the first example:arr1.copyWithin(1, 3)
copies elements starting from index 3 to the end and pastes them starting at index 1 inarr1
. It changes the original array, resulting in[ 'a', 'd', 'e', 'd', 'e' ]
.
In the second example:
arr2.copyWithin(0, 3, 4)
copies the element at index 3 and pastes it at index 0 inarr2
. It also changes the original array, resulting in[ 'd', 'b', 'c', 'd', 'e' ]
.
In both cases, the original arrays are modified in place.
every():
every()
method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value(true or false). It can only be implemented in the function.console.log(".................every() in JS.................") function oddeven1(ele){ return ele%2===0 } let x=[2,4,6,8].every(oddeven1) console.log(x) //true
filter():
filter()
method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.console.log("..............filter() in JS ..................") function oddeven2(ele){ return ele%2===0 } var x=[2,4,6,7,8,9,11,23].filter(oddeven2) console.log(x) //[ 2, 4, 6, 8 ]
forEach():
forEach()
method executes a provided process once for each array element.console.log(".............forEach().....................") function oddeven(ele) { process.stdout.write(ele + ' '); } var x = [2, 4, 6, 7, 8, 9, 11, 23, 77].forEach(oddeven); //2 4 6 7 8 9 11 23 77
Here we used
process.stdout.write
unlikeconsole.log
, which automatically adds a new line character at the end of the output,process.stdout.write
does not add a new line. This is useful when you want to print multiple items on the same line. You can use console.log as well no problem with that.indexOf():
indexOf()
method returns the first index at which a given element can be found in the array, or -1 if it is not present.console.log(".................indexOf() in JS ...............") const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; console.log(beasts.indexOf('bison')); //1 console.log(beasts.indexOf('ant')) //0 console.log(beasts.indexOf('Kushal')) //-1
lastIndexOf():
lastIndexOf()
method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backward, starting at fromIndex.console.log("..................lastIndexOf() i JS ..........") const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo']; console.log(animals.lastIndexOf('Dodo')); //3 console.log(animals.lastIndexOf('Kushal')); //-1
map():
map()
method creates a new array populated with the results of calling a provided function on every element in the calling array.console.log(".............map()..........................") function oddeven3(ele){ return ele*2 } var x=[2,4,6,7,8,9].map(oddeven3) console.log(x) //[ 4, 8, 12, 14, 16, 18 ]
map() will return A new array with each element being the result of the callback function.
reverse():
reverse()
method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, the elements' order in the array will be turned in the direction opposite to that previously stated.console.log(".............reverse()in JS..................") const cars1 = ["Saab", "Volvo", "BMW"]; console.log(cars1.reverse()) //[ 'BMW', 'Volvo', 'Saab' ]
The reference to the original array is now reversed. Note that the array is reversed
in place
, and no copy is made. This means it will change permanently the original array.slice():
slice()
method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.console.log("..................slice() In JS ..............") const num=[12,34,"hi","jhon"] const result=num.slice(1,3) console.log(result) // [ 34, 'hi' ] console.log(num) //[ 12, 34, 'hi', 'jhon' ] // not going to change the original array console.log(num.slice(0)) //[ 12, 34, 'hi', 'jhon' ] // slice(0) will going to print all the elements in an array console.log(num.slice(2)) //[ 'hi', 'jhon' ] // here we put slice(2) it means it will print all the elements // from the 2th index console.log(num.slice()) //[ 12, 34, 'hi', 'jhon' ] // it will also going to print all the elements from a given array
A new array containing the extracted elements and start and end values are optional.
splice():
splice()
method changes the contents of an array by removing or replacing existing elements and/or adding new elements.Syntax : `splice(start, deleteCount, item1, item2, itemN)console.log("...........splice() in JS.............") // removing and inserting an elemnet using splice() const name=["Rahul","Ram","Kushal"] name.splice(1,2,"HI") console.log(name) //[ 'Rahul', 'HI' ] // add elemnts using splice() const name1=["Rahul","Ram","Kushal"] name1.splice(1,0,"Ram",123) console.log(name1) //[ 'Rahul', 'Ram', 123, 'Ram', 'Kushal' ] // if you want to add elements using splice() then // your count value should be '0' all the time .
some():
some()
method tests whether at least one element in the array passes the test implemented by the provided function. It returnstrue
if, in the array, it finds an element for which the provided function returns true; otherwise, it returnsfalse.
It doesn't modify the array. It will check if at least one condition is true then it returns true else false.console.log( "..............some() in JS............") function even(ele){ return ele%2==0 } let nums1=[1,3,5,7,9,1].some(even) let nums2=[1,3,5,8,9,1].some(even) console.log(nums1)//false [no one is even number over here ] console.log(nums2)//true [becuase in nums2 we have one even number.]
sort():
sort()
method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending.console.log("_______________sort() in jS_______________") const arraystr = ["a","b","c","aa"]; arraystr.sort(); console.log(arraystr); //[ 'a', 'aa', 'b', 'c' ]
In Javascript, the sort() function is working fine in the case of
strings
only but when it comes to numbers the problem arises.example :
const array12 = [12,34,56,78,9,100]; array12.sort(); console.log(array12); //[100,12,34,56,78,9]
sort() in js follows alphabetic order and it also considers the number as a string Here
'[100,12,34,56,78,9]`
is output because if you compare the first number of 100 and the first number of 9 then in 100 we have 1 and in 9 we have 9 only. since 1<9, 100 comes first. And it follows the ASCII value.To fix this we use
callback function
orCustom Function
Example:const sortcall= [12,34,56,78,9,100]; sortcall.sort(function(a,b) { return a-b }); //Here if we write b-a that becomes your descending order //and a-b is your ascending order . console.log(sortcall); //[9,12,34,56,78,100]
fill():
fill()
method is a built-in method in JavaScript arrays that allows you to change all elements in an array with a static value. It modifies the original array and returns the modified array.syntax: array.fill(value, start, end);
console.log("------------------------fill()................") //fill(value, start=optional, end=optional) var score=[12,34,5,6,"demo"] // using range in fill method console.log(score.fill(0,4,5)) //[ 12, 34, 5, 6, 0 ] // here 0 is the value that we want to insert and 4 is the starting range where 5 is the ending range . console.log(score.fill("0",2,5)) //[ 12, 34, '0', '0', '0' ] // replace all the elements and fill with 0 console.log(score.fill(0)) //[ 0, 0, 0, 0, 0 ]
find():
find()
method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, "undefined will return". And find will work in function only.console.log(".................find().......................") const array123 = [5, 12, 8, 130, 44]; const found = array123.find(element => element > 10); console.log(found) //12
findindex():
findIndex()
method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.console.log("...................findindex()................") const array1234 = [5, 12, 8, 130, 44,12]; const found1 = array1234.findIndex(element => element > 10); console.log(found1) // return 1 since the first 12 is in index 1
findLast():
findLast()
method iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, undefined is returned.console.log("..................findLast()...............") const arr12 = [5, 120, 50, 130, 44]; const found12 = arr12.findLast((element) => element > 45); console.log(found12); // 130 is the ans because if we start //counting from reverse then for greater than 45 only //one number that is 130.
findLastIndex():
findLastIndex()
method iterates the array in reverse order and returns the index of the first element that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.console.log("................findLastIndex()............") const arr123 = [5, 120, 50, 130, 44]; const found123 = arr123.findLastIndex((element) => element > 45); console.log(found123) //3
includes():
includes()
method determines whether an array includes a certain value among its entries, returning true or false as appropriate.console.log("................includes()....................") const arr31 = [1, 2, 3]; console.log(arr31.includes(2)); //true console.log(arr31.includes(-1)) //false
join():
join()
method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.console.log("....................join()..............") elements = ["Fire","Air","Water"] console.log(elements.join()); // expected output: "Fire,Air,Water" console.log(elements.join('*')); // expected output: "Fire*Air*Water" console.log(elements.join('-')); // expected output: "Fire-Air-Water"
array.from():
Array.from()
static method creates a new, shallow-copied Array instance from an iterable or array-like object.console.log("...................array.from()...........") console.log(Array.from('foo')); // expected output: Array ["f", "o", "o"] console.log(Array.from('234566')); // expected output: Array ['2','3','4','5','6','6']
keys():
keys()
method returns a new Array Iterator object that contains the keys for each index in the array.console.log("......................keys().................") let city = ["California", "Barcelona", "Paris", "Kathmandu"]; let x1=city.keys(); for (let k of x1){ console.log(k); // 0 1 2 3 }
values():
values()
method returns a new array iterator object that iterates the value of each index in the array.console.log("....................values()...............") let city = ["x",12,"y"]; let x12=city.values(); for (let i of x12){ console.log(i) // x 12 y }
Conclusion π₯β‘οΈ
JavaScript arrays are versatile and powerful data structures that simplify data manipulation in web development. Whether you're building a simple web page or a complex web application, arrays are essential for storing, retrieving, and processing data efficiently. By mastering the array methods and techniques discussed in this article, you'll be better equipped to harness the full potential of JavaScript arrays in your projects.
Thanks for reading all the way to the end! π
If you have any questions, please use the comments section π¬
Let's connect! Find me on the web π
If you have any Queries or Suggestions, feel free to reach out to me.
Happy Coding :)β€οΈ
Subscribe to my newsletter
Read articles from Kushal Das directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Kushal Das
Kushal Das
A Full Stack Web Developer | A Mentor | A freelancerπ» | Data science enthusiastic | Open source enthusiastic | Create and write content | Enjoy learning new techs | love meeting new people! π