Lets assume I have the following array:
const arr = [ '0', 'parentNode', 'children', '0', 'values' ]
And my goal is to cut the array until when a certain string matches (everything after that string).
So if I choose children as the string, the result would be:
const arr = [ '0', 'parentNode', 'children']
My current implementation works, I am creating a big function and iterating over the array, push each element to a new array when a condition holds....
But I would like to have a more elegant solution, maybe a oneliner.
In Python, this is possible, how would this look like in JavaScript?
CodePudding user response:
There are lots of ways.
indexof
(findIndex
if you need to use a callback because the comparison is more complicated) and slice
:
const index = arr.indexOf(target);
const result = index < 0 ? [] : arr.slice(index);
A simple loop:
const result = [];
let found = false;
for (const element of arr) {
found = found || element === target;
if (found) {
result.push(element);
}
}
let found = false;
const result = arr.filter(element => {
found = found || element === target;
return found;
});
CodePudding user response:
This is the one-liner solution:
arr.slice(0, arr.indexOf('children') 1)
It performs well, because uses native code (V8, SpiderMonkey, etc...). But does not handle errors. If no 'children'
is found, you'll receive empty array.