JavaScript Array is a special variable that can store more than one value at a time. The values can be numeric, character, string, etc.
Syntax:
1 | var arrayName = [value1, value2, value3, ...]; |
Example:
1 | var names = ['John', 'Kavish', 'Warner']; |
There are also built-in properties and methods in JavaScript that you can use as needed.
- Array Length
- Array Join()
- Forach()
- Sort()
- Reverse()
- Find() and FindIndex()
- Include()
- Every() And Some()
- Push() And Pop()
- Unshift() And Shift()
- Map()
- Filter()
- Reduce()
Array Length
The length of the array returns a numeric value.
Syntax:
1 | arrayName.length |
Example:
1 2 3 | var names = ['John', 'Warner', 'Peter']; var length = names.length; console.log(length);//3 |
Array Join()
We use array join to convert an array into a string in JavaScript. We use a specific separator to separate strings.
Syntax:
1 | arrayName.join(seperator); |
Let’s take example:
If we do not add any separator then it will add default comma(,).
1 2 3 | var names = ['John', 'Warner', 'Peter']; var namesString = names.join(); console.log(namesString);//John,Warner,Peter |
If you pass the separator then it separates the value by that separator.
1 2 3 | var names = ['John', 'Warner', 'Peter']; var namesString = names.join('/'); console.log(namesString);//John/Warner/Peter |
Array forEach()
We use array forEach() to apply an operation on array elements.
There are three syntax for the array forEach().
1 2 3 | array.forEach( (element, index) => //operation ); |
1 2 3 4 | array.forEach((element, index) => { //Operation } ); |
1 2 3 | array.forEach(function(element, index) { //Operation }); |
Here are three writing styles of the code of forEach in JavaScript but all three will give the same output.
1 2 | var names = ['John', 'Warner', 'Peter']; names.forEach((element, index) => console.log(`${element} has ${index} index.`)); |
1 2 3 4 5 | var names = ['John', 'Warner', 'Peter']; names.forEach((element, index) => { console.log(`${element} has ${index} index.`); } ); |
1 2 3 4 | var names = ['John', 'Warner', 'Peter']; names.forEach(function(element, index) { console.log(`${element} has ${index} index.`); }); |
Output:
1 2 3 | John has 0 index. Warner has 1 index. Peter has 2 index. |
Sort()
It is used to sort an array. By default, the array will be sorted in ascending order.
Syntax:
1 | array.sort(); |
We use the following method to sort an array:
- a-b = positive which means the element b will sort before a.
- a-b = negative which means the element a will sort before b.
- a-b = zero which means the element will stay in the same position.
Let’s take examples to understand:
Sort the array from lowest to highest order:
1 2 3 | var marks = [90, 45, 50, 30, 80, 75]; marks.sort((a,b) => a-b); console.log(marks);//[ 30, 45, 50, 75, 80, 90 ] |
Sort the array from highest to lowest order:
1 2 3 | var marks = [90, 45, 50, 30, 80, 75]; marks.sort((a,b) => b-a); console.log(marks);//[ 90, 80, 75, 50, 45, 30 ] |
Reverse()
It is used to reverse the order of an array. The array on which the reverse() is applied, the original array changes.
Syntax:
1 | array.reverse(); |
Example:
- const numbers = [1,2,3,4]
- numbers.reverse() => [4,3,2,1]
1 2 3 4 5 6 7 | const numbers = [1,2,3,4]; numbers.reverse(); console.log(numbers);//[ 4, 3, 2, 1 ] var names = ['Troposal', 'Rakesh', 'John', 'David']; names.reverse(); console.log(names);//[ 'David', 'John', 'Rakesh', 'Troposal' ] |
Find() and FindIndex()
Returns the first element or index that passes the testing function.
Syntax: Both array methods use same syntax.
1 | array.find(function(element, index, array), thisArg) |
1 | array.findIndex(function(element, index, array), thisArg) |
Find(): Returns the first element that passes the testing function. If no match then returns undefine.
findIndex(): Returns the first index of element that passes the testing function. If no match then returns -1.
Example of find():
1 2 3 4 5 6 7 8 | var marks = [55, 90, 45, 50, 30, 80, 75]; //Find the first that is greater than 50 var overFifty = marks.find((element) => element > 50); console.log(overFifty);//55 //Find the first that is greater than 90 var overNinety = marks.find((element) => element > 90); console.log(overNinety);//undefine |
Example of findIndex():
1 2 3 4 5 6 7 8 | var marks = [55, 90, 45, 50, 30, 80, 75]; //Find the first index that is greater than 50 var overFifty = marks.findIndex((element) => element > 50); console.log(overFifty);//0 //Find the first index that is greater than 90 var overNinety = marks.findIndex((element) => element > 90); console.log(overNinety);//-1 |
Include()
It returns a boolean to indicate if an array includes a specific value.
Syntax:
1 | array.includes(value, fromIndex) |
Note: Value is a case sensitive.
Example:
1 2 3 | const fruits = ['apple', 'banana', 'mango']; const fruitsIncluded = fruits.includes('apple'); console.log(fruitsIncluded);//true |
if you pass index value to 1 then it will start checking the value from 1 index and it will return “false” because apple is available on zero index.
Example:
1 2 3 | const fruits = ['apple', 'banana', 'mango']; const fruitsIncluded = fruits.includes('apple', 1); console.log(fruitsIncluded);//false |
Value is a case sensitive if you pass “Apple” then it will return “false”.
1 2 3 | const fruits = ['apple', 'banana', 'mango']; const fruitsIncluded = fruits.includes('Apple'); console.log(fruitsIncluded);//false |
Every() And Some()
Both JavaScript method returns boolean based on a function.
every(): Returns a boolean to indicate if every element in the array matches the criteria provided.
some(): Returns a boolean to indicate if an array contains some elements that match the criteria provided.
Syntax:
1 | array.every(function(element, index, array), thisArg); |
1 | array.every(function(element, index, array), thisArg); |
Example of every() JavaScript function: In the below example, all the elements are greater than 20 so it will return true.
1 2 3 | var marks = [55, 90, 45, 50, 30, 80, 75]; var some = marks.every(element => element > 20); console.log(some);true |
In the below example, all elements of the array are not starting with ‘a’ so it will return false.
1 2 3 | const fruits = ['apple', 'banana', 'mango']; var some = fruits.every(element => element.startsWith('a')); console.log(some);//false |
Example of some() JavaScript function: In the below example, checking if some elements are greater than 50. If yes then returns true otherwise it will return false.
1 2 3 | var marks = [55, 90, 45, 50, 30, 80, 75]; var some = marks.some(element => element > 50); console.log(some);//true |
Lets take other Example: In the below example, checking the some name of fruits are starting with ‘a’ if yes then return true otherwise return false.
1 2 3 4 5 6 | const fruits = ['apple', 'banana', 'mango']; var some = fruits.some(element => element.startsWith('a')); console.log(some);//true var some = fruits.some(element => element.startsWith('c')); console.log(some);//false |
Push() And Pop() function in JavaScript
Both of these array methods manipulates the length and contents of the array by adding and removing the data to and from the end of an array.
Push():
It is used to add the content to the end of an array.
Syntax:
1 | array.push(elements); |
It returns length property of the newly changed array.
Example: In the below example, one more fruit has been added at the end of the array using push method of the JavaScript.
1 2 3 | var fruits = ['apple', 'banana', 'mango']; fruits.push('orange'); console.log(fruits);//[ 'apple', 'banana', 'mango', 'orange' ] |
Pop():
It is used to remove the content from end of the array.
Syntax:
1 | array.pop(); |
It returns length property of the newly changed array.
Example:
1 2 3 | const fruits = ['apple', 'banana', 'mango']; fruits.pop(); console.log(fruits);//[ 'apple', 'banana' ] |
Unshift() And Shift() function in JavaScript
Both of these array methods manipulate the length and contents of an array by adding and removing data to and from the beginning of an array.
Unshift():
It is used to add the content at the beginning of an array.
Syntax:
1 | array.unshift(element); |
Example:
1 2 3 | const fruits = ['apple', 'banana', 'mango']; fruits.unshift('orange'); console.log(fruits);//[ 'orange', 'apple', 'banana', 'mango' ] |
Shift():
It is used to remove the content from the beginning of an array.
Syntax:
1 | array.shift(); |
Example:
1 2 3 | const fruits = ['apple', 'banana', 'mango']; fruits.shift(); console.log(fruits);//[ 'banana', 'mango' ] |
Map() and FlatMap() method in JavaScript Array
map():
It creates a new array based on the function applied to each element in the array you are interacting over.
Syntax:
1 | var newArray = array.map(function(value, index, array), thisArg); |
Example: In the below example, 5 will be added in each elements of the array.
1 2 3 | var marks = [55, 90, 45, 50, 30, 80, 75]; var marks = marks.map((mark) => mark + 5); console.log(marks);//[ 60, 95, 50, 55, 35, 85, 80 ] |
Example: You can make a new array for showing the full name.
1 2 3 4 5 6 7 8 9 | var names = [ { firstName: "John", lastName: "Annand" }, { firstName: "David", lastName: "Warner" }, { firstName: "Rakesh", lastName: "Tiwari" }, { firstName: "Barak", lastName: "Obama" } ]; var fullName = names.map((name) => `${name.firstName} ${name.lastName}`); console.log(fullName);//[ 'John Annand', 'David Warner', 'Rakesh Tiwari', 'Barak Obama' ] |
flatMap():
The flatMap() method uses a mapping function to map each element in an array and then flattens the results into a new array.
Syntax:
1 | var newArray = array.flatMap(function(value, index, array), thisArg); |
Example: flatMap() method has splitted the each letter in the below code.
1 2 3 | var fruits = ['apple', 'banana', 'mango']; var splitFruits = fruits.flatMap((fruit) => fruit.split('')); console.log(splitFruits);//["a", "p", "p", "l", "e", "b", "a", "n", "a", "n", "a", "m", "a", "n", "g", "o"] |
Filter() method in JavaScript Array
It creates a new array based on whether or not elements pass the test provided by the function provided.
Syntax:
1 | var newArray = array.filter(function(element, index, array), thisArg); |
Example: In below example, getting an array which obtains marks more than 50.
1 2 3 | var marks = [55, 90, 45, 50, 30, 80, 75]; var marksOverFifty = marks.filter(mark => mark > 50); console.log(marksOverFifty);//[ 55, 90, 80, 75 ] |
Let’s take another example: In the below example, we will get an array which have more than 9000 salary.
1 2 3 4 5 6 7 8 | var employees = [ { name: "John", email: "john@gmail.com", salary: 10000 }, { name: "David", email: "david@gmail.com", salary: 11000 }, { name: "Joy", email: "joy@gmail.com", salary: 9000 }, { name: "Smith", email: "smith@gmail.com", salary: 7000 } ]; var employees = employees.filter(employee => employee.salary > 9000); console.log(employees); |
Output of above example:
1 2 3 4 | Output: [ { name: 'John', email: 'john@gmail.com', salary: 10000 }, { name: 'David', email: 'david@gmail.com', salary: 11000 } ] |
Reduce() Function in JavaScript
It executes a reducer function against each element in an array and returns a single value. The returned value is the accumulated value.
Syntax:
1 | array.reduce(function(accumulator, currentValue, index, array), initialValue); |
- accumulator – It is required and it is accumulated or total.
- currentValue – Required.
- index – Optional.
- array – Option.
- initialValue – Optional.
Example: Below example it gives total sum of the value of the array.
1 2 3 | var bills = [100, 300, 500, 50]; var totalBill = bills.reduce((total, bill) => total + bill); console.log(totalBill);//950 |
Conclusion
You have checked the JavaScript array and methods. Many interviewer asks the questions about the methods map, filter, push and pop, unshift and shift, every and some, find and findIndex etc.
You can check the more JavaScript topic:
Declaring JavaScript Variables: Var, Let and Const
Cookies, Local Storage and Session Storage in JavaScript