1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
In this blog you will understand how to get the first N javascript array elements (Slice, splice, destructuring, for loop, filter, and lodash.take()), common errors, and a fun coding problem to sharpen your skills.
slice()
Method: My Preferred Choice to get first N elements of JS arrayThe slice()
method is a versatile and non-destructive way to handle arrays.
let fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
let firstThree = fruits.slice(0, 3);
console.log(firstThree); // ['Apple', 'Banana', 'Cherry']
splice()
Method: Handle with Caresplice()
, while similar in name to slice()
, modifies the original array, which can be a source of confusion.
let fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
let removed = fruits.splice(0, 3);
console.log(removed); // ['Apple', 'Banana', 'Cherry']
console.log(fruits); // Remaining elements: ['Date', 'Elderberry']
Destructuring offers a concise way to extract multiple elements based on their position.
let fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
let [first, second, third] = fruits;
console.log(first, second, third); // Apple Banana Cherry
A traditional for
loop gives you control over the number of iterations. If we need to element wise operation, or checks then we can use this familiar approach. But requires manual handling of array bounds, and can cause Index out of bounds (undefined elements returned from array) if not careful.
let fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
let firstThree = [];
for (let i = 0; i < 3; i++) {
firstThree.push(fruits[i]);
}
console.log(firstThree); // ['Apple', 'Banana', 'Cherry']
We can use Array.filter() method with filter condition on each element in the array. But:
filter()
iterates over the entire array, even if we need a need a small part of the array.const fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
const n = 2;
const first2 = fruits.filter((element, index) => index < n);
console.log(first2); // 👉️ ['Apple', 'Banana']
If you are already using Lodash library in your project, then can use take()
function. It returns a new array and does not modify the original one.
let _ = require('lodash');
let fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
let firstTwo = _.take(fruits, 2);
console.log(firstTwo); // ['Apple', 'Banana']
splice()
instead of slice()
: As shown, splice()
modifies the original array, which can lead to unexpected results.undefined
. To avoid surprises, always ensure you are within array’s length, while accessing array elements.In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.
As a programmer, you have a long list of books to read. Write a function to select the first N books from your list.
Problem (JavaScript)
/**
* Returns the first N elements of an array.
*
* @param {Array} array - An array of book titles.
* @param {number} n - Number of titles to return.
* @return {Array} An array containing the first N book titles.
*/
function selectBooks(array, n) {
// > > > 👉 Write code here 👈 < < <
}
// Driver code:
let books = ['JavaScript: The Good Parts', 'Eloquent JavaScript', 'You Don't Know JS', 'JavaScript & JQuery', 'Learn JavaScript Visually'];
console.log(selectBooks(books, 3)); // ['JavaScript: The Good Parts', 'Eloquent JavaScript', 'You Don't Know JS']
Please attempt before seeing the Answer:
function selectBooks(array, n) {
return array.slice(0, n);
}
Explanation:
n
is greater than the array’s length by returning the entire array.Hopefully, this blogpost gave you several approaches to access first few elements of Javascript array. Keep coding! 🚀👨💻
Feel free to reach out!