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']
>>>
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With