How to find all elements in a given array except for the first one using JavaScript ?
Last Updated :
03 Jan, 2024
To find all elements in a given array except for the first one using JavaScript, we have multiple approaches, In this article, we will learn how to find all elements in a given array except for the first one.
These are the multiple methods by which we can find all elements in a given array except for the first one
In this method, we will use a for loop to grab all the elements except the first. We know that in an array the first element is present at index ‘0’. We will run a loop from 1 to array.length and save those remaining elements to another array.
Example: In this example, we will be using a for loop to find all elements in an array except for the first element.
Javascript
const print = (arr) => {
const find = []
let k = 0
for (let i = 1; i < arr.length; i++) {
find[k] = arr[i]
k++
}
return find
}
const arr = [1, 2, 3, 4, 5]
console.log(print(arr))
|
The slice() is a method that returns a slice of an array. It takes two arguments, the start and end index.
Example: In this example, we will be using the slice() method to find all elements in an array except for the first element.
Javascript
const print = (arr) => {
return arr.slice(1)
}
const arr = [10, 20, 30, 40, 50]
console.log(print(arr))
|
Output
[ 20, 30, 40, 50 ]
The Array.filter() method is used to create a new array with elements from the existing array which satisfies the condition.
Example: In this example, we will be using the filter() method to find all elements in an array except for the first element.
Javascript
const print = (arr) => {
return arr.filter((x, y) => y != 0)
}
const arr = [10, 20, 30, 40, 50]
console.log(print(arr))
|
Output
[ 20, 30, 40, 50 ]
The Array.reduce() is used to perform the function on each element of an array and form a single element.
Example: In this example, we will be using the reduce() method to find all elements in an array except for the first element.
Javascript
const print = (arr) => {
return arr.reduce(
(a, x, i) =>
(i == 0) ? a :
a.concat(x), [])
}
const arr = [10, 20, 30, 40, 50]
console.log(print(arr))
|
Output
[ 20, 30, 40, 50 ]
The JavaScript Array shift() Method removes the first element of the array thus reducing the size of the original array by 1.
Example: In this example, we are using shift() Method.
Javascript
function func() {
let array = [34, 234, 567, 4];
let value = array.shift();
console.log(array);
}
func();
|
Share your thoughts in the comments
Please Login to comment...