const fruits = ['apple', 'banana', 'orange', 'kiwi', 'mango']; const citrusFruits = fruits.slice(2, 4); console.log(citrusFruits); // Output: ['orange', 'kiwi']
splice method is used to add or remove elements from an array. It can be used to remove elements by specifying the starting index and the number of elements to remove. Additionally, you can also add elements by providing the index, the number of elements to remove, and the elements to add.
Example of removing elements:
const numbers = [1, 2, 3, 4, 5]; numbers.splice(2, 2); console.log(numbers); // Output: [1, 2, 5]
Example of adding elements:
const colors = ['red', 'blue', 'green']; colors.splice(1, 0, 'yellow', 'orange'); console.log(colors); // Output: ['red', 'yellow', 'orange', 'blue', 'green']
reverse method reverses the order of elements in an array. It modifies the original array, so use it with caution if you want to preserve the original order.
const numbers = [1, 2, 3, 4, 5]; numbers.reverse(); console.log(numbers); // Output: [5, 4, 3, 2, 1]
concat method allows you to merge two or more arrays into a single array. It does not modify the original arrays; instead, it returns a new array containing the concatenated elements.
const arr1 = ['a', 'b', 'c']; const arr2 = ['d', 'e', 'f']; const mergedArray = arr1.concat(arr2); console.log(mergedArray); // Output: ['a', 'b', 'c', 'd', 'e', 'f']
join method is used to create a string from the elements of an array. It concatenates the elements using a specified separator and returns the resulting string.
const fruits = ['apple', 'banana', 'orange']; const fruitsString = fruits.join(', '); console.log(fruitsString); // Output: 'apple, banana, orange'
const numbers = [1, 2, 3, 4, 5]; const element = numbers; console.log(element); // Output: 3
Can I use the
slice method to extract elements from an array without specifying the ending index?
Yes, if you omit the ending index, the
slice method will extract all elements from the starting index to the end of the array.
splice method modify the original array?
splice method modifies the original array by adding or removing elements.
Is it possible to reverse the order of elements in an array without modifying the original array?
reverse method modifies the original array in place.
Can I concatenate more than two arrays using the
Yes, you can concatenate multiple arrays by providing them as arguments to the
How can I access an element at a specific index in an array?
You can use array indexing, such as
array[index], to access an element at a particular index in an array.