Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get all elements after a certain index in javascript

in python doing this would be as simple as:

mylist = ['red','blue','green','yellow']
print(mylist[1:])
'blue','green','yellow'

when i tried this in JavaScript mylist[0] returned 'red' etc. but when i tried doing something like mylist[1:] in JavaScript it was not correct syntax. what is a good method of doing this in JavaScript? basically get all elements after a specified index. and to be specific, i am doing this in node.js but i do not think that matters much.

to clarify directly out of python what i would like.

>>> mylist = ['red','green','blue','yello']
>>> print(mylist[1:])
['green', 'blue', 'yello']
>>> 
like image 556
riyoken Avatar asked Sep 08 '13 03:09

riyoken


People also ask

How do you find all occurrences of an element in an array in JavaScript?

To get the index of all occurrences of an element in a JavaScript array: Create an empty array, that will store the indexes. Use a for loop and loop from 0 up to the array's length. For each iteration of the loop, check if the element at that index is equal to the specific element.

How do you get the index of an item in a list JavaScript?

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Can you use includes () with an array in JavaScript?

includes() You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How do you get a specific value from an array in JavaScript?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.


1 Answers

You can use the slice method like below:

mylist = ['red','blue','green','yellow'];
console.log(mylist.slice(1));

Output:

["blue", "green", "yellow"] 

Demo | Array slice method - MDN Link

like image 129
Harry Avatar answered Oct 19 '22 18:10

Harry