0

How do I remove 1 and 3 from below array in array?

[[1,2], [3,4,5]]

[[2],[4,5]]

was thinking about pop() but stuck somewhere.

1

5 Answers 5

1

Try to use JavaScript built-in function shift().

var a = [[1,2], [3,4,5]];

a.map(item => { 
    item.shift();
    return item;
});

console.log(a); // [[2], [4, 5]]

Official guide: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

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

Comments

0

You can use map and splice:

const a = [[1,2], [3,4,5]];

console.log(
  a.map(item => item.splice(1))
)

Basically you're mapping each item of the array with the same array without the first element (since splice mutate the array).

If you want have a copy also of the inner array, then you should use slice instead.

Comments

0

Loop through the main array as you normally would, like

    let array = [[1,2], [3,4,5]]
    for (let el of array) {
         // Now you'll be accessing each array inside the main array,
         // YOu can now remove the first element using .shift()
         el.shift();
     }

Comments

0

You can map the array, and got all items, but the the 1st, with Array.slice():

const arr = [[1,2], [3,4,5]];

const result = arr.map(item => item.slice(1));

console.log(result);

Comments

0

Try this :

var arr = [[1,2], [3,4,5]];

for (var innerArray of arr) {
  // Using array.splice()
  for (var element of innerArray) {
  	if (element === 1 || element === 3) innerArray.splice(innerArray.indexOf(element), 1);
  }
}

console.log(arr);

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.