0

I have 2 dimensional array myArray:

[
  [ '567576', 'John', 'Doe' ],
  [ '098897', 'John', 'Doe' ],
  [ '543539', 'John', 'Doe' ],
  [ '234235', 'John', 'Doe' ],
  [ '345348', 'John', 'Doe' ],
  [ '432574', 'John', 'Doe' ]
]

Is it possible to create a new array from myArray starting from a certain first value? For example create a new array starting from id 543539. Anything above the array containing 543539 will not be added.

4
  • 1
    yes it is possible. Commented Jul 18, 2022 at 17:39
  • SO isn't a coding service; what have you attempted here? I'd look into Array.map() and Array.filter(). Commented Jul 18, 2022 at 17:39
  • In fact, almost everything imaginable is possible in js :D Commented Jul 18, 2022 at 17:41
  • NewArray = myArray.slice(myArra.findIndex((el)=>el[0]==543539)) Commented Jul 18, 2022 at 17:42

3 Answers 3

1

You can make use of findIndex() which returns the index of the first item that matches the condition. Combine it with slice() to cut your array at the specific position:

const myArray = [
  ['567576', 'John', 'Doe'],
  ['098897', 'John', 'Doe'],
  ['543539', 'John', 'Doe'],
  ['234235', 'John', 'Doe'],
  ['345348', 'John', 'Doe'],
  ['432574', 'John', 'Doe']
]

console.log(myArray.slice(myArray.findIndex(item => item[0] === "543539")));

Sign up to request clarification or add additional context in comments.

Comments

0

Sure, assuming all the internal arrays are structured the same way, you can do something like let newArray = myArray.filter(innerArray => Number(innerArray[0]) > 543539)

Edit: This is assuming you want all subarrays where the first item is a number larger than 54539, as opposed to finding all of the subarrays that physically follow the first occurrence of a subarray with 54539 as the first value

Comments

0

Yes, that is possible and straightforward process. You can use the javascript map method which returns a new array

newArray = myArray.map(item=> item[0])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.