JavaScript Array Methods
Data Types: Array Methods
Can you explain the function of the array splice() method?
View Answer:
Syntax: arr.splice(start[, deleteCount, elem1, ..., elemN]);
let arr = ['I', 'study', 'JavaScript'];
arr.splice(1, 1); // from index 1 remove 1 element
console.log(arr); // ["I", "JavaScript"]
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months); // [ 'Jan', 'Feb', 'March', 'April', 'June' ]
months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]
How do negative array indexes work?
View Answer:
let arr = [1, 2, 5];
// from index -1 (one step from the end)
// delete 0 elements,
// then insert 3 and 4
arr.splice(-1, 0, 3, 4);
console.log(arr); // 1,2,3,4,5
What methods are available in JavaScript to add elements to an array?
View Answer:
- Using
push()
to add elements to the end of the array:
let arr = ['a', 'b', 'c'];
arr.push('d');
console.log(arr); // Logs: ['a', 'b', 'c', 'd']
- Using
unshift()
to add elements to the beginning of the array:
let arr = ['a', 'b', 'c'];
arr.unshift('0');
console.log(arr); // Logs: ['0', 'a', 'b', 'c']
- Using
splice()
to add elements at a specific index in the array:
let arr = ['a', 'b', 'c'];
arr.splice(1, 0, '1.5');
console.log(arr); // Logs: ['a', '1.5', 'b', 'c']
In the splice()
example, the first parameter is the index where new elements should be added, the second parameter is the number of elements to remove (0 in this case, since we're only adding), and the rest are the elements to add.
Can you explain the function of the array slice() method?
View Answer:
Syntax: slice(start, end);
let arr = ['t', 'e', 's', 't'];
console.log(arr.slice(1, 3)); // e,s (copy from 1 to 3)
console.log(arr.slice(-2)); // s,t (copy from -2 till the end)
What is the key difference between the array splice and slice methods?
View Answer:
// Array Slice Method *
let arr = ['t', 'e', 's', 't'];
console.log(arr.slice(1, 3)); // e,s (copy from 1 to 3)
console.log(arr.slice(-2)); // s,t (copy from -2 till the end)
console.log(arr); // ['t', 'e', 's', 't']; no change to the original array
// Array Splice Method **
let arr2 = [1, 2, 5];
console.log(arr2.splice(-1, 0, 3, 4)); // returns []
// returns an empty array because it was ran before it was created
console.log(arr2); // 1,2,3,4,5 – modified the original array
Can you please explain the function of the array concat() method?
View Answer:
Syntax: arr.concat(arg1, arg2...);
let arr = [1, 2];
// create an array from: arr and [3,4]
console.log(arr.concat([3, 4])); // 1,2,3,4
// create an array from: arr and [3,4] and [5,6]
console.log(arr.concat([3, 4], [5, 6])); // 1,2,3,4,5,6
// create an array from: arr and [3,4], then add values 5 and 6
console.log(arr.concat([3, 4], 5, 6)); // 1,2,3,4,5,6
///////////////////////////////
let arr = [1, 2];
let arrayLike = {
0: 'something',
length: 1,
};
console.log(arr.concat(arrayLike)); // 1,2,[object Object]
///////////////////////////////
let arr = [1, 2];
let arrayLike = {
0: 'something',
1: 'else',
[Symbol.isConcatSpreadable]: true,
length: 2,
};
console.log(arr.concat(arrayLike)); // 1,2,something,else
Can you explain the function of the array forEach() method?
View Answer:
Syntax: arr.forEach(callback function(item, index, array) );
// Using an Arrow Function
let myFunction = (item, index) => {
console.log(index + ':' + item);
};
const fruits = ['apple', 'orange', 'cherry'];
fruits.forEach(myFunction);
// Using an Function Declaration
const fruits2 = ['apple', 'orange', 'cherry'];
fruits2.forEach(myFunction);
function myFunction(item, index) {
console.log(index + ':' + item);
}
Why can’t you use a return statement in a forEach loop?
View Answer:
const array = [1, 2, 3, 4, 5];
let sum = 0;
array.forEach((element) => {
sum += element;
return; // This return statement has no effect
});
console.log(sum); // Output: 15
Additionally, break and continue statements are not valid statements, resulting in a Syntax error.
How do the array methods indexOf()
, lastIndexOf()
, and includes()
differ from their string counterparts?
View Answer:
How does the array indexOf() method work?
View Answer:
Syntax: arr.indexOf(searchElement[, fromIndex]);
let arr = [1, 0, false];
console.log(arr.indexOf(0)); // 1
console.log(arr.indexOf(false)); // 2
console.log(arr.indexOf(null)); // -1
Can you explain the function of the array lastIndexOf() method?
View Answer:
Syntax: arr.lastIndexOf(searchElement[, fromIndex]);
let numbers = [2, 5, 9, 2];
console.log(numbers.lastIndexOf(2)); // 3
console.log(numbers.lastIndexOf(7)); // -1
console.log(numbers.lastIndexOf(2, 3)); // 3
console.log(numbers.lastIndexOf(2, 2)); // 0
console.log(numbers.lastIndexOf(2, -2)); // 0
console.log(numbers.lastIndexOf(2, -1)); // 3
How does the array includes() method function?
View Answer:
Syntax: arr.includes(valueToFind[, fromIndex]);
[1, 2, 3]
.includes(2) // true
[(1, 2, 3)].includes(4) // false
[(1, 2, 3)].includes(3, 3) // false
[(1, 2, 3)].includes(3, -1) // true
[(1, 2, NaN)].includes(NaN); // true
What are the key differences between array includes() and indexOf() methods?
View Answer:
// Using includes() method to check for NaN
const array1 = [NaN];
if (array1.includes(NaN)) {
console.log('true. NAN was found in the array'); // true. NAN was found in the array
}
// Using indexOf() method to check for NaN
const array2 = [NaN];
if (array2.indexOf(NaN) == -1) {
console.log('NaN not found in the array'); // NaN not found in the array
}
How does the array find() method work?
View Answer:
Syntax: arr.find[callback(element[, index[, array]]](, thisArg));
// Simple Implementation
const array1 = [5, 12, 8, 130, 44];
const found = array1.find((element) => element > 10);
console.log(found);
// expected output: 12
// Implementation on Array Objects
let users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Pete' },
{ id: 3, name: 'Mary' },
];
let user = users.find((item) => item.id == 1);
console.log(user.name); // expected output: John
You should remember that index 0 gets interpreted as a falsie value in conditional statement checks on the find method.
Can you explain the function of the array findIndex() method?
View Answer:
Syntax: arr.findIndex[callback( element[, index[, array]] ](, thisArg));
// Simple Implementation
const array1 = [5, 12, 8, 130, 44];
const found = array1.findIndex((element) => element > 10);
console.log(found);
// expected output: 1
// Implementation on Array Objects
let users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Pete' },
{ id: 3, name: 'Mary' },
];
let user = users.findIndex((item) => item.id == 1);
console.log(user); // expected output: 0
How does the array filter() method function?
View Answer:
Syntax: arr.filter(callback(item, index, array);
let users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Pete' },
{ id: 3, name: 'Mary' },
];
// returns array of the first two users
let someUsers = users.filter((item) => item.id < 3);
console.log(someUsers.length); // 2
// filter method with a callback function
function isBigEnough(value) {
return value >= 10;
}
let filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
Can you explain the function of the array sort(fn) method?
View Answer:
Syntax: arr.sort([compareFunction]);
let arr = [1, 2, 15];
// the method reorders the content of arr
arr.sort();
console.log(arr); // 1, 15, 2
// The FIX for sorting numbers
function compareNumeric(a, b) {
if (a > b) return 1;
if (a == b) return 0;
if (a < b) return -1;
}
let arr = [1, 2, 15];
arr.sort(compareNumeric);
console.log(arr); // 1, 2, 15
How does the array map() method work?
View Answer:
let result = arr.map(function (item, index, array) {
// returns the new value instead of item
});
let arr = ['Bilbo', 'Gandalf', 'Nazgul'];
let lengths = arr.map((item) => item.length);
console.log(lengths); // 5,7,6
Can you explain the function of the array reverse() method?
View Answer:
Syntax: arr.reverse();
const nums = [1, 2, 3];
console.log(nums); // [1, 2, 3]
// Now in reverse
nums.reverse();
console.log(nums); // [3, 2, 1]
// This is how you reverse string using the reverse method
let word = 'Hello';
// turn word to an array ['H', 'e', 'l', 'l', 'o']
let wordArr = Array.from(word);
wordArr.reverse(); // reverse ['H', 'e', 'l', 'l', 'o']
console.log(wordArr); // wordArr = ["o", "l", "l", "e", "H"]
We should note that you cannot use the reverse method to reverse a string. Its strictly used for arrays, but this can give insight into the reverse method's first step to reversing string. Simply (It’s not that simple), it turns the string into an array.
Can you explain the function of the array split() method?
View Answer:
Syntax: string.split(delimiter[, optional: number]);
let names = 'Bilbo, Gandalf, Nazgul';
let arr = names.split(', ');
console.log(arr);
for (let name of arr) {
console.log(`A message to ${name}.`); // A message to Bilbo (and other names)
}
// Using optional second parameter to return the first two strings to the array
let arr = 'Bilbo, Gandalf, Nazgul, Saruman'.split(', ', 2);
console.log(arr); // return Bilbo, Gandalf
How does the array join() method function?
View Answer:
Syntax: arr.join([separator]);
let arr = ['Wind', 'Water', 'Fire'];
arr.join(); // 'Wind,Water,Fire'
arr.join(', '); // 'Wind, Water, Fire'
arr.join(' + '); // 'Wind + Water + Fire'
arr.join(''); // 'WindWaterFire'
Can you explain the function of the array reduce() method?
View Answer:
let value = arr.reduce(
function (accumulator, item, index, array) {
// ...
},
[initial]
);
let arr = [1, 2, 3, 4, 5];
let result = arr.reduce((sum, current) => sum + current, 0);
console.log(result); // 15
The reduce method does not execute the function for array elements without values or change the original array.
How does the array reduceRight() method function?
View Answer:
let value = arr.reduceRight(
function (accumulator, item, index, array) {
// ...
},
[initial]
);
let arr = [1, 2, 3, 4, 5];
let result = arr.reduceRight((sum, current) => sum + current, 0);
console.log(result); // 15
Conversely, the reduce() method does the same thing but from left to right.
Can you explain how the array isArray() method functions?
View Answer:
Array.isArray(value);
// all following calls return true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array('a', 'b', 'c', 'd'));
Array.isArray(new Array(3));
// Little known fact: Array.prototype itself is an array:
Array.isArray(Array.prototype); // returns true
// all following calls return false
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray('Array');
Array.isArray(true);
Array.isArray(false);
Array.isArray(new Uint8Array(32));
Array.isArray({ __proto__: Array.prototype });
It is better to use the typeof operator to determine the object type.
What are typed arrays in JavaScript and how are they primarily used?
View Answer:
Web applications become more powerful, adding features like audio and video manipulation, and access to raw data using WebSockets. It becomes clear that there are times when it would be helpful for JavaScript code to manipulate raw binary data easily. This point is the time where typed arrays come in. Each entry in a JavaScript typed array is a raw binary value in one of several supported formats, from 8-bit integers to 64-bit floating-point numbers.
However, typed arrays are not to be confused with standard arrays, as calling Array.isArray() on a typed array returns false. Moreover, not all methods available for standard arrays get supported by typed arrays (e.g., push and pop).
JavaScript typed arrays divide the implementation into buffers and views for optimal flexibility and efficiency. A buffer (implemented by the ArrayBuffer object) is an object that represents a block of data; it has no format and no way to retrieve its contents. A view is required to access the memory contained in a buffer. A view, which turns the data into a typed array, provides a context: a data type, beginning offset, and the number of elements.
// Creating a typed array
const buffer = new ArrayBuffer(8); // Create an 8-byte buffer
const typedArray = new Int32Array(buffer); // Create a typed array with 32-bit integers
// Manipulating the typed array
typedArray[0] = 42;
typedArray[1] = 10;
// Accessing values from the typed array
console.log(typedArray[0]); // Output: 42
console.log(typedArray[1]); // Output: 10
What is the difference between Array push() and unshift() methods?
View Answer:
const array = [1, 2, 3];
// Using push() to add elements to the end of the array
array.push(4);
console.log(array); // Output: [1, 2, 3, 4]
// Using unshift() to add elements to the beginning of the array
array.unshift(0);
console.log(array); // Output: [0, 1, 2, 3, 4]
How do you remove an element from an array in JavaScript?
View Answer:
const array = [1, 2, 3, 4, 5];
// Remove element at index 2
array.splice(2, 1);
console.log(array); // Output: [1, 2, 4, 5]