Home > front end >  How do I match an element value and collect successive elements
How do I match an element value and collect successive elements

Time:07-15

How do I get elements after -p or --name in this array

['-p', 'player', '1', '--name', 'player1', 'name']

CodePudding user response:

Get the index of the element and splice the array at that index ( 1 if you don't want that element):

const arr = ['-p', 'player', '1', '--name', 'player1', 'name'];
var index = arr.indexOf("--name");

arr.slice(  index) // or just index if you also want "--name"

CodePudding user response:

function getNextElements(arr, str) {
    let res = [];
    for (let i = 0; i < arr.length; i  ) {
        if (arr[i] === str) {
            for (let j = i   1; j < arr.length; j  ) {
                res.push(arr[j])
            }
        }
    }
    return res
}

let arr = ['-p', 'player', '1', '--name', 'player1', 'name']
console.log(getNextElements(arr, '--name')) //Result: [ 'player1', 'name' ]
console.log(getNextElements(arr, '-p')) //Result: [ 'player', '1', '--name', 'player1', 'name' ]

Here, I have used simple For loops to come to the answer. The function takes an array and a string, after which we want elements.

  • Related