Java Script Array: A Detailed Guide
Table of contents
- Introduction to JavaScript Arrays
- Creating Arrays
- Using Array Literals
- Using the
Array
Constructor
- Accessing Array Elements
- Modifying Arrays
- Adding Elements
- Removing Elements
- Updating Elements
- Array Methods
push()
pop()
shift()
unshift()
concat()
slice()
splice()
indexOf()
includes()
forEach()
map()
filter()
reduc
e()
- Best Practices
- Standard Coding Structures
1. Introduction to JavaScript Arrays
Arrays are list-like objects used to store multiple values in a single variable. Arrays can hold any type of data, including strings, numbers, objects, and other arrays.
2. Creating Arrays
Using Array Literals
// Example 1
let fruits = ['Apple', 'Banana', 'Orange'];
console.log(fruits); // Output: ['Apple', 'Banana', 'Orange']
// Example 2
let numbers = [1, 2, 3, 4, 5];
console.log(numbers); // Output: [1, 2, 3, 4, 5]
// Example 3
let mixedArray = [1, 'two', true, null];
console.log(mixedArray); // Output: [1, 'two', true, null]
Using the Array
Constructor
// Example 4
let fruits = new Array('Apple', 'Banana', 'Orange');
console.log(fruits); // Output: ['Apple', 'Banana', 'Orange']
// Example 5
let numbers = new Array(1, 2, 3, 4, 5);
console.log(numbers); // Output: [1, 2, 3, 4, 5]
// Example 6
let emptyArray = new Array(5); // Creates an array with 5 empty slots
console.log(emptyArray); // Output: [ <5 empty items> ]
3. Accessing Array Elements
let fruits = ['Apple', 'Banana', 'Orange'];
// Example 1
console.log(fruits[0]); // Output: 'Apple'
// Example 2
console.log(fruits[2]); // Output: 'Orange'
// Example 3
console.log(fruits[fruits.length - 1]); // Output: 'Orange' (last element)
4. Modifying Arrays
Adding Elements
let fruits = ['Apple', 'Banana'];
// Example 1: Using push()
fruits.push('Orange');
console.log(fruits); // Output: ['Apple', 'Banana', 'Orange']
// Example 2: Using unshift()
fruits.unshift('Strawberry');
console.log(fruits); // Output: ['Strawberry', 'Apple', 'Banana', 'Orange']
// Example 3: Direct assignment
fruits[fruits.length] = 'Grapes';
console.log(fruits); // Output: ['Strawberry', 'Apple', 'Banana', 'Orange', 'Grapes']
Removing Elements
let fruits = ['Apple', 'Banana', 'Orange'];
// Example 1: Using pop()
fruits.pop();
console.log(fruits); // Output: ['Apple', 'Banana']
// Example 2: Using shift()
fruits.shift();
console.log(fruits); // Output: ['Banana', 'Orange']
// Example 3: Using splice()
fruits.splice(1, 1);
console.log(fruits); // Output: ['Apple']
Updating Elements
let fruits = ['Apple', 'Banana', 'Orange'];
// Example 1
fruits[1] = 'Mango';
console.log(fruits); // Output: ['Apple', 'Mango', 'Orange']
// Example 2
fruits[fruits.length - 1] = 'Pineapple';
console.log(fruits); // Output: ['Apple', 'Mango', 'Pineapple']
// Example 3
let index = fruits.indexOf('Apple');
if (index !== -1) {
fruits[index] = 'Kiwi';
}
console.log(fruits); // Output: ['Kiwi', 'Mango', 'Pineapple']
5. Array Methods
push()
let numbers = [1, 2, 3];
numbers.push(4);
console.log(numbers); // Output: [1, 2, 3, 4]
numbers.push(5, 6);
console.log(numbers); // Output: [1, 2, 3, 4, 5, 6]
pop()
let numbers = [1, 2, 3, 4];
let last = numbers.pop();
console.log(numbers); // Output: [1, 2, 3]
console.log(last); // Output: 4
shift()
let numbers = [1, 2, 3, 4];
let first = numbers.shift();
console.log(numbers); // Output: [2, 3, 4]
console.log(first); // Output: 1
unshift()
let numbers = [2, 3, 4];
numbers.unshift(1);
console.log(numbers); // Output: [1, 2, 3, 4]
numbers.unshift(0, -1);
console.log(numbers); // Output: [-1, 0, 1, 2, 3, 4]
concat()
let arr1 = [1, 2];
let arr2 = [3, 4];
let arr3 = arr1.concat(arr2);
console.log(arr3); // Output: [1, 2, 3, 4]
let arr4 = arr1.concat(arr2, [5, 6]);
console.log(arr4); // Output: [1, 2, 3, 4, 5, 6]
slice()
let numbers = [1, 2, 3, 4, 5];
let part = numbers.slice(1, 3);
console.log(part); // Output: [2, 3]
let endPart = numbers.slice(3);
console.log(endPart); // Output: [4, 5]
splice()
let numbers = [1, 2, 3, 4, 5];
// Example 1: Removing elements
let removed = numbers.splice(1, 2);
console.log(numbers); // Output: [1, 4, 5]
console.log(removed); // Output: [2, 3]
// Example 2: Adding elements
numbers.splice(1, 0, 2, 3);
console.log(numbers); // Output: [1, 2, 3, 4, 5]
// Example 3: Replacing elements
numbers.splice(1, 2, 'two', 'three');
console.log(numbers); // Output: [1, 'two', 'three', 4, 5]
indexOf()
let fruits = ['Apple', 'Banana', 'Orange', 'Banana'];
// Example 1
let index = fruits.indexOf('Banana');
console.log(index); // Output: 1
// Example 2
let lastIndex = fruits.lastIndexOf('Banana');
console.log(lastIndex); // Output: 3
// Example 3
let notFound = fruits.indexOf('Grapes');
console.log(notFound); // Output: -1
includes()
let fruits = ['Apple', 'Banana', 'Orange'];
// Example 1
console.log(fruits.includes('Banana')); // Output: true
// Example 2
console.log(fruits.includes('Grapes')); // Output: false
// Example 3
console.log(fruits.includes('Orange', 2)); // Output: true
// Example 4
console.log(fruits.includes('Orange', 3)); // Output: false
forEach()
let numbers = [1, 2, 3, 4, 5];
// Example 1
numbers.forEach(function(number) {
console.log(number);
});
// Output: 1 2 3 4 5
// Example 2
numbers.forEach((number, index) => {
console.log(`${index}: ${number}`);
});
// Output: 0: 1 1: 2 2: 3 3: 4 4: 5
// Example 3
numbers.forEach((number, index, array) => {
array[index] = number * 2;
});
console.log(numbers); // Output: [2, 4, 6, 8, 10]
map()
let numbers = [1, 2, 3, 4, 5];
// Example 1
let doubled = numbers.map(number => number * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]
// Example 2
let squared = numbers.map(number => number ** 2);
console.log(squared); // Output: [1, 4, 9, 16, 25]
// Example 3
let strings = numbers.map(number => `Number: ${number}`);
console.log(strings); // Output: ['Number: 1', 'Number: 2', 'Number: 3', 'Number: 4', 'Number: 5']
filter()
let numbers = [1, 2, 3, 4, 5, 6];
// Example 1
let evens = numbers.filter(number => number % 2 === 0);
console.log(evens); // Output: [2, 4, 6]
// Example 2
let odds = numbers.filter(number => number % 2 !== 0);
console.log(odds); // Output: [1, 3, 5]
// Example 3
let greaterThanThree = numbers.filter(number => number > 3);
console.log(greaterThanThree); // Output: [4, 5, 6]
reduce()
let numbers = [1, 2, 3, 4, 5];
// Example 1
let sum = numbers.reduce((total, number) => total + number, 0);
console.log(sum); // Output: 15
// Example 2
let product = numbers.reduce((total, number) => total * number, 1);
console.log(product); // Output: 120
// Example 3
let max = numbers.reduce((max, number) => (number > max ? number : max), numbers[0]);
console.log(max); // Output: 5
6. Best Practices
- Use array methods like
push
,pop
,shift
,unshift
,map
,filter
, andreduce
to manipulate arrays efficiently. - Use descriptive variable names to make your code more readable.
- Avoid using the
new Array()
constructor when creating arrays with known elements. - Prefer
const
overlet
for array declarations if you don’t plan to reassign the array.
7. Standard Coding Structures
Initializing Arrays
const numbers = [1, 2, 3, 4, 5];
const emptyArray = [];
Looping Through Arrays
// Using for loop
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
// Using for...of loop
for (const number of numbers) {
console.log(number);
}
// Using forEach method
numbers.forEach(number => {
console.log(number);
});
Transforming Arrays
// Using map to create a new array
const doubled = numbers.map(number => number * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]
// Using filter to create a new array
const evens = numbers.filter(number => number % 2 === 0);
console.log(evens); // Output: [2, 4]
Reducing Arrays
// Using reduce to accumulate values
const sum = numbers.reduce((total, number) => total + number, 0);
console.log(sum); // Output: 15
Interview Questions
Beginner Level
Question1: How do you create an array in JavaScript?
Answer:
// Using array literals
let fruits = ['Apple', 'Banana', 'Orange'];
// Using the Array constructor
let numbers = new Array(1, 2, 3, 4, 5);
Question2: How do you access the first and last element of an array?
Answer:
let fruits = ['Apple', 'Banana', 'Orange'];
let first = fruits[0];
let last = fruits[fruits.length - 1];
console.log(first); // Output: 'Apple'
console.log(last); // Output: 'Orange'
Question3: How do you add an element to the end of an array?
Answer:
let fruits = ['Apple', 'Banana'];
fruits.push('Orange');
console.log(fruits); // Output: ['Apple', 'Banana', 'Orange']
Question4: How do you remove the last element of an array?
Answer:
let fruits = ['Apple', 'Banana', 'Orange'];
let last = fruits.pop();
console.log(fruits); // Output: ['Apple', 'Banana']
console.log(last); // Output: 'Orange'
Question5: How do you add an element to the beginning of an array?
Answer:
let fruits = ['Banana', 'Orange'];
fruits.unshift('Apple');
console.log(fruits); // Output: ['Apple', 'Banana', 'Orange']
Question6: How do you remove the first element of an array?
Answer:
let fruits = ['Apple', 'Banana', 'Orange'];
let first = fruits.shift();
console.log(fruits); // Output: ['Banana', 'Orange']
console.log(first); // Output: 'Apple'
Question7: How do you find the index of an element in an array?
Answer:
let fruits = ['Apple', 'Banana', 'Orange'];
let index = fruits.indexOf('Banana');
console.log(index); // Output: 1
Question8: How do you check if an array includes a certain element?
Answer:
let fruits = ['Apple', 'Banana', 'Orange'];
let hasBanana = fruits.includes('Banana');
console.log(hasBanana); // Output: true
Question9: How do you iterate over an array using a for loop?
Answer
let fruits = ['Apple', 'Banana', 'Orange'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Output: 'Apple', 'Banana', 'Orange'
Question10: How do you iterate over an array using the forEach
method?
Answer:
let fruits = ['Apple', 'Banana', 'Orange'];
fruits.forEach(function(fruit) {
console.log(fruit);
});
// Output: 'Apple', 'Banana', 'Orange'
Intermediate Level
Question11: How do you create a new array by transforming each element in an existing array using map
?
Answer:
let numbers = [1, 2, 3, 4];
let doubled = numbers.map(function(number) {
return number * 2;
});
console.log(doubled); // Output: [2, 4, 6, 8]
Question12: How do you filter an array to include only even numbers using filter
?
Answer:
let numbers = [1, 2, 3, 4, 5, 6];
let evens = numbers.filter(function(number) {
return number % 2 === 0;
});
console.log(evens); // Output: [2, 4, 6]
Question13: How do you combine all elements of an array into a single value using reduce
?
Answer:
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce(function(total, number) {
return total + number;
}, 0);
console.log(sum); // Output: 15
Question14: How do you concatenate two arrays?
Answer:
let arr1 = [1, 2];
let arr2 = [3, 4];
let combined = arr1.concat(arr2);
console.log(combined); // Output: [1, 2, 3, 4]
Question15: How do you slice an array to get a subarray?
Answer:
let numbers = [1, 2, 3, 4, 5];
let subArray = numbers.slice(1, 3);
console.log(subArray); // Output: [2, 3]
Question16: How do you remove, replace, or add elements to an array using splice
?
Answer:
let numbers = [1, 2, 3, 4, 5];
// Remove elements
let removed = numbers.splice(1, 2);
console.log(numbers); // Output: [1, 4, 5]
console.log(removed); // Output: [2, 3]
// Add elements
numbers.splice(1, 0, 2, 3);
console.log(numbers); // Output: [1, 2, 3, 4, 5]
// Replace elements
numbers.splice(1, 2, 'two', 'three');
console.log(numbers); // Output: [1, 'two', 'three', 4, 5]
Question17: How do you flatten a nested array?
Answer:
let nestedArray = [1, [2, 3], [4, [5, 6]]];
let flattened = nestedArray.flat(2);
console.log(flattened); // Output: [1, 2, 3, 4, 5, 6]
Question18: How do you create a new array with the results of calling a function for every array element using map
?
Answer:
let numbers = [1, 2, 3, 4, 5];
let squared = numbers.map(function(number) {
return number ** 2;
});
console.log(squared); // Output: [1, 4, 9, 16, 25]
Question19: How do you find the first element in an array that satisfies a provided testing function using find
?
Answer:
let numbers = [1, 2, 3, 4, 5];
let firstEven = numbers.find(function(number) {
return number % 2 === 0;
});
console.log(firstEven); // Output: 2
Question20: How do you check if at least one element in an array passes a test using some
?
Answer:
let numbers = [1, 2, 3, 4, 5];
let hasEven = numbers.some(function(number) {
return number % 2 === 0;
});
console.log(hasEven); // Output: true