What is Array and what are the different methods to create/declare the array?
An array is a special variable, which can hold more than one value in a single variable.
Methods to Create/Declare Arrays
const original = [1, 2, 3];
const copy = [...original];
//Output[1, 2, 3]
const array2 = [..."JavaScript"];
console.log(array2);
//['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']
Method Name | Description | Example |
---|---|---|
Array Literal Notation | The most common way to create an array using square brackets [] . | const arr = [1, 2, 3, 4, 5]; |
Array Constructor | Creates an array using the Array constructor. Can be used to create arrays with a specified length or with elements. | |
Array.of() | Creates a new Array instance with a variable number of arguments. |
|
Array.from() | Creates a new Array instance from an array-like or iterable object. |
|
Spread Operator | Expands an array into its individual elements or converts an iterable into an array. |
|
Array.fill() | Creates an array with a specific length and fills it with a specified value. |
|
Can you summarizing the most basic and commonly used array methods in JavaScript?
Here’s a table summarizing some of the most basic and commonly used array methods in JavaScript, including their descriptions and examples:
Name | Description | Example |
---|---|---|
Array.length | Property that returns the number of elements in an array. |
|
Array.push() | Adds one or more elements to the end of an array and returns the new length of the array. |
|
Array.pop() | Removes the last element from an array and returns that element. |
|
Array.shift() | Removes the first element from an array and returns that element. |
|
Array.unshift() | Adds one or more elements to the beginning of an array and returns the new length of the array. |
|
Array.concat() | Combines or merge two or more arrays and returns a new array. |
|
Array.join() | Joins all elements of an array into a string, separated by a specified delimiter. |
|
Array.toString() | Used to convert an array to a string. |
|
Array.splice() | used for modifying an array by adding or removing elements. It directly alters the original array and returns an array of removed elements (if any). | Removing Elements
Adding Elements
Replacing Elements |
Array.slice() | Create a shallow copy of a portion of an array into a new array object. It does not modify the original array but rather returns a new array containing the selected elements.array.slice(start, end) start: Start position. Default is 0. end: End position. Default is last element. |
|
Array.forEach() | Used for iterating over arrays and performing actions on each element. |
|
Array.map() | Creates a new array by applying a function to each element of an existing array. |
|
Array.filter() | Creates a new array with all elements that pass the test implemented by the provided function. It is useful for filtering elements based on certain conditions. |
|
Array.find() and Array.findLast() | Returns the first element in the array that satisfies the provided testing function. The Array.findLast() Returns the value of the last element in an array that pass a test |
Finding an Object by Property
|
Array.findIndex() and Array.findLastIndex() | Returns the index of the first element in the array that satisfies the provided testing function. The Array.findLastIndex() Returns the index of the last element in an array that pass a test. |
|
Array.sort() | Sorts the elements of an array in place and returns the array. The default sorting order is according to string Unicode code points |
Array with String elements
Sorting Objects by a Property
|
Array.reverse() | Reverses the elements of an array in place and returns the array. |
Reversing a String Array
Reversing an Array of Objects
|
Array.copyWithin() | Copies a portion of an array to another location within the same array, without modifying its size. It allows you to replace part of the array with a copy of another part of the same array.array.copyWithin(target, start, end) |
|
Array.entries() | returns a new Array Iterator object that contains the key/value pairs for each index in the array. |
|
Array.every() | Tests whether all elements in an array pass a provided test function. It returns a Boolean value (true or false ), |
|
Array.fill() | Fill all or part of an array with a static value, from a start index to an end index. This method modifies the original array and returns the updated array.array.fill(value, start, end) |
|
Array.flat() | Used to flatten nested arrays. It creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. |
|
Array.from() | Create a new array instance from an array-like or iterable object. This method provides a way to convert various types of objects into arrays. It also allows you to transform the elements of the array using a mapping function.Array.from(object, mapFunction, thisValue) |
Convert a NodeList (array-like object) to an array
Converting a Set or Map to an Array |
Array.includes() | Determines whether an array includes a certain element.array.includes(valueToFind, fromIndex); | |
Array.indexOf() | Search the array for an element and returns its positionarray.indexOf(searchElement, fromIndex); | |
Array.reduce() | Reduce the values of an array processes each element of an array to reduce it to a single value, using a function that updates an accumulator. (going left-to-right) | |
Array.reduceRight() | The Array.reduceRight() method in JavaScript works similarly to Array.reduce() , but it processes the array elements from right to left instead of left to right. | |
Array.some() | Tests whether at least one element in the array passes the test implemented by the provided function. | |
Array.toReversed() | Array.toReversed() method is a new method introduced in ECMAScript 2024 that returns a new array with the elements in reverse order without modifying the original array. |
|
Array.with() | The Array.with() method is a new addition to JavaScript introduced in ECMAScript 2024. It provides a way to create a new array with one or more elements replaced at specified indices, without modifying the original array. | |
How to Count Element Occurrences from Array?
To count the occurrences of elements in an array, we can use the Array.reduce()
method. Here’s a simple way to do it:
const array = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana'];
const countOccurrences = array.reduce((accumulator, item) => {
// If the item is already a key in the accumulator object, increment its count
if (accumulator[item]) {
accumulator[item]++;
} else {
// Otherwise, add the item to the accumulator with a count of 1
accumulator[item] = 1;
}
return accumulator;
}, {});
console.log(countOccurrences);
// Output: { apple: 2, banana: 3, orange: 1 }
How to check object/variable type is Array?
There are four methods to check if a variable is an array in JavaScript.
Methods to check Array | Code |
---|---|
Array.isArray() | |
instanceof Operator | |
Object.prototype.toString.call() | |
constructor Property | |
How do you find min and max values without Math functions?
You can also find the minimum and maximum values in an array by sorting the array and then accessing the first and last elements. Here’s how you can do it without using Math.min()
or Math.max()
functions, but with the Array.sort()
method.
function findMinMaxUsingSort(arr) {
if (arr.length === 0) {
throw new Error('Array cannot be empty');
}
// Copy the array to avoid mutating the original
const sortedArray = arr.slice().sort((a, b) => a - b);
const min = sortedArray[0];
const max = sortedArray[sortedArray.length - 1];
return { min, max };
}
// Example usage
const numbers = [5, 3, 9, 1, 6];
const { min, max } = findMinMaxUsingSort(numbers);
console.log('Min:', min); // Output: Min: 1
console.log('Max:', max); // Output: Max: 9
What is the difference between slice and splice?
Feature | slice() | splice() |
---|---|---|
Purpose | Creates a shallow copy of a portion of the array. | Adds or removes items from the array in place. |
Original Array | Unchanged | Modified |
Return Value | A new array with the extracted elements. | An array of removed elements. |
Parameters | start (optional), end (optional) | start , deleteCount (optional), items (optional) |
Modification | Does not modify the original array. | Modifies the original array. |
Usage Example | array.slice(1, 3) | array.splice(1, 2, 'new1', 'new2') |
Deep Copy | Creates a shallow copy (not deep). | No copy, modifies the array directly. |
What does it mean when slice()
creates a shallow copy (not a deep copy)?
When we say that Array.slice()
creates a “shallow copy” of an array, it means that the new array created by slice()
is a new array instance, but the elements inside the new array are not themselves copied deeply. Instead, they are references to the same objects that are in the original array. This distinction is important for understanding how slice()
handles objects and nested arrays.
Example 1: Shallow Copy with Primitives
const original = [1, 2, 3];
const copied = original.slice();
console.log(copied);// Output: [1, 2, 3]
copied[0] = 99;
console.log(original); // Output: [1, 2, 3] (original array remains unchanged)
console.log(copied); // Output: [99, 2, 3]
Example 2: Shallow Copy with Objects
const original = [{ name: 'Alice' }, { name: 'Bob' }];
const copied = original.slice();
console.log(copied); // Output: [{ name: 'Alice' }, { name: 'Bob' }]
copied[0].name = 'Charlie';
console.log(original); // Output: [{ name: 'Charlie' }, { name: 'Bob' }]
console.log(copied); // Output: [{ name: 'Charlie' }, { name: 'Bob' }]
What is destructuring assignment?
Destructuring assignment is a syntax in JavaScript that allows you to keyphrase unpack values from arrays or properties from objects into distinct variables. It provides a concise and readable way to extract data from arrays and objects.
const numbers = [1, 2, 3, 4];
const [first, second, third] = numbers;
console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(third); // Output: 3
//-----------Object
const person = {
name: 'Alice',
age: 30,
job: 'Engineer'
};
const { name, age, job } = person;
console.log(name); // Output: Alice
console.log(age); // Output: 30
console.log(job); // Output: Engineer
//-----------nested Object------
const user = {
name: 'Bob',
address: {
street: '123 Main St',
city: 'Somewhere'
}
};
// Nested object destructuring
const { name, address: { street, city } } = user;
console.log(name); // Output: Bob
console.log(street); // Output: 123 Main St
console.log(city); // Output: Somewhere
const [a = 1, b = 2,c = 6] = [3,5];
console.log(a); // Output: 3
console.log(b); // Output: 5
console.log(c); // Output: 6 default value
How do you swap variables in destructuring assignment?
let a = 5;
let b = 10;
// Swap the values of a and b
[a, b] = [b, a];
console.log(a); // Output: 10
console.log(b); // Output: 5
What will be the Output […”JavaScript”]?
The spread operator (...
) to convert a string into an array of its individual characters.
console.log([..."JavaScript"]);
// Output: ['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']
How do you remove falsy values from an array?
//Using filter
const array = [0, 1, false, 2, '', 3, null, 4, undefined, 5, NaN];
const filteredArray = array.filter(Boolean);
console.log(filteredArray);
// Output: [1, 2, 3, 4, 5]
//Using reduce
const reduceArray = array.reduce((acc, item) => {
if (item) acc.push(item);
return acc;
}, []);
console.log(reduceArray );
How can you obtain unique values from an array?
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray);
// Output: [1, 2, 3, 4, 5]
// Using reduce and includes
const uniqueArray1 = array.reduce((accumulator, value) => {
if (!accumulator.includes(value)) {
accumulator.push(value);
}
return accumulator;
}, []);
console.log(uniqueArray1 );
// Output: [1, 2, 3, 4, 5]
How do you empty an array?
//1. Setting Length to 0
let array = [1, 2, 3, 4, 5];
array.length = 0;
console.log(array); // Output: []
//2. Using splice() Method
let array = [1, 2, 3, 4, 5];
array.splice(0, array.length);
console.log(array); // Output: []
//3. Reassigning to an Empty Array
let array = [1, 2, 3, 4, 5];
array = [];
console.log(array); // Output: []
What will happen if you either set an array’s length
property to 0
or reassign the array variable to an empty array ([]
)?
Scenario 1: Setting length to 0: The original array is emptied, and all references to it (including myObj.arry_ref
) will reflect this change.
let myArray = [1, 2, 3, 4, 5];
let myObj = { array_ref: myArray };
myArray.length = 0;
console.log(myArray);//Output []
console.log(myObj); //Output {array_ref: []}
Scenario2: Reassigning the Array Variable []: The myArray variable is assigned a new empty array, but myObj.arry_ref continues to point to the original array, which remains unchanged.
It creates a new array, so if other parts of your code hold references to the original array, they will not see this change.
let myArray = [1, 2, 3, 4, 5];
let myObj = { array_ref: myArray };
myArray = [];
console.log(myArray);//Output []
console.log(myObj); //Output { array_ref: [1,2,3,4,5]}
What methods have the same name for both arrays and strings in JavaScript, and how do they differ?
Method/Property | Description | Array Example | String Example |
---|---|---|---|
length | Returns the number of elements or characters. | let arr = [1, 2, 3]; console.log(arr.length); // 3 | let str = "hello"; console.log(str.length); // 5 |
concat | Combines multiple arrays or strings into one. | let arr1 = [1, 2]; let arr2 = [3, 4]; console.log(arr1.concat(arr2)); // [1, 2, 3, 4] | let str1 = "hello"; let str2 = "world"; console.log(str1.concat(" ", str2)); // "hello world" |
slice | Extracts a portion of the array or string. | let arr = [1, 2, 3, 4]; console.log(arr.slice(1, 3)); // [2, 3] | let str = "hello world"; console.log(str.slice(0, 5)); // "hello" |
indexOf | Finds the index of the first occurrence of an element or substring. | let arr = [1, 2, 3]; console.log(arr.indexOf(2)); // 1 | let str = "hello world"; console.log(str.indexOf("world")); // 6 |
lastIndexOf | Finds the index of the last occurrence of an element or substring. | let arr = [1, 2, 3, 2]; console.log(arr.lastIndexOf(2)); // 3 | let str = "hello world world"; console.log(str.lastIndexOf("world")); // 12 |
includes | Checks if an array contains a certain element or if a string contains a substring. | let arr = [1, 2, 3]; console.log(arr.includes(2)); // true | let str = "hello world"; console.log(str.includes("world")); // true |
toString | Converts the array or string to a string. | let arr = [1, 2, 3]; console.log(arr.toString()); // "1,2,3" | let str = "hello"; console.log(str.toString()); // "hello" |
reverse | Reverses the order of elements or characters. | let arr = [1, 2, 3]; console.log(arr.reverse()); // [3, 2, 1] | let str = "hello"; console.log(str.split("").reverse().join("")); // "olleh" |
To more about the JavaScript String, Click here.