Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript local storage. Get only first 3 elements?

Getting and returning elements from local storage to be displayed is simple:

let element = JSON.parse(localStorage.getItem('element'));
return element.elements

Assuming element is the key and elements are a bunch of elements in the key.

But, how would I get only the first 3 elements?

I currently have this (but I think there will be a better way to do it):

let firstelement = element.elements[0];
let secondelement = element.elements[1];
let thirdelement = element.elements[2];

I'm not sure what to do after this.

like image 206
SilentDev Avatar asked Jun 22 '26 16:06

SilentDev


1 Answers

According to MDN:

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

So try this:

let element = JSON.parse(localStorage.getItem('element'));
var selection = element.elements.slice(0, 3);

Kudos to CertainPerformance for suggesting to use slice in a comment.

like image 158
Sol Avatar answered Jun 24 '26 06:06

Sol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!