ArticleZip > Get First And Last Elements In Array Es6 Way Duplicate

Get First And Last Elements In Array Es6 Way Duplicate

In JavaScript, working with arrays is a common task for developers. One frequent need is to grab the first and last elements of an array efficiently. Fortunately, ES6 provides some handy methods that make this process a breeze.

Let's dive into how you can accomplish this in a clean and concise manner using ES6 features. We'll cover getting the first and last elements of an array, and then handle the case of arrays with duplicate elements.

To get the first element of an array in ES6, you can use array destructuring combined with the spread operator. Here's a simple example:

Js

const arr = [1, 2, 3, 4, 5];
const [first] = arr;
console.log(first); // Output: 1

In this snippet, we destructure the `arr` array by assigning its first element to the `first` variable. This approach is concise and readable, making it easy to extract the first element of an array.

To retrieve the last element of an array, you can also leverage array destructuring along with the spread operator. Here's how you can do it:

Js

const arr = [1, 2, 3, 4, 5];
const [, , , , last] = arr;
console.log(last); // Output: 5

In this example, we skip the first four elements using commas and then assign the last element to the `last` variable. This technique allows you to efficiently access the last element of an array in just a line of code.

Now, let's address the scenario where your array contains duplicate elements. If you want to get all occurrences of the first and last elements in an array with duplicates, you can use the `filter` method. Here's how you can achieve this:

Js

const arr = [1, 2, 3, 4, 3, 5];
const first = arr.find(element => element === arr[0]);
const last = arr.find(element => element === arr[arr.length - 1]);
console.log(first); // Output: 1
console.log(last); // Output: 5

In this code snippet, we use the `find` method to locate the first and last occurrences of the elements matching the first and last elements of the array, respectively. This approach ensures that you handle duplicate elements correctly and retrieve the desired values.

By utilizing ES6 features like array destructuring, spread operator, and array methods like `find`, you can efficiently extract the first and last elements of an array in JavaScript, even when dealing with duplicates. These modern JavaScript techniques help streamline your code and enhance readability, making your development tasks more straightforward and enjoyable. Happy coding!