0

I have a js 2d array

var a = [["a","b","c","d","e","f"]]

I need to discard the last and insert at the first position

var result = [["new","a","b","c","d","e"]]    //<------ "f" has to be discarded

I have tried with

a.unshift("new")

How do I do it?

3
  • 4
    Is your array really 2-dimensional? Commented Dec 13, 2020 at 7:15
  • Yes 2 dim array Commented Dec 13, 2020 at 7:16
  • @CodeGuy so can you have more than just one array inside the outer array then? Commented Dec 13, 2020 at 7:17

3 Answers 3

4

Use unshift to add new values to the beginning of the array and pop to remove values from the end.

let a = ["a", "b", "c", "d", "e", "f"];
a.unshift('new');
a.pop();
console.log(a);

Also, in your example - a is an array within array, so perform this on the inner array.

To be even more generic, you can extract this to function and perform this on every inner array with map:

let a = [
  ["a", "b", "c", "d", "e", "f"]
];
let result = a.map(innerArr => {
  innerArr.unshift('new');
  innerArr.pop();
  return innerArr;
});
console.log(result);

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

6 Comments

I need a 2d array, this is not a 2d array
@CodeGuy a 1-D array nested in a 2-D array, is still 1-D. What you need is to realize that unshift() and pop() solves your problem.
@CodeGuy I added a clarification
I know that, But I am expecting the efficient and reliable technique
Or @CodeGuy a copy/paste solution? OmriAttiya answers your concerns here succinctly.
|
2

You can first splice it and then use unshift

var a = [
  ["a", "b", "c", "d", "e", "f"]
]
a[0].splice(-1, 1);
a[0].unshift('new');
console.log(a)

Comments

1

var a = [["a","b","c","d","e","f"]]
a[0].unshift('new');
a[0].pop();
console.log(a);

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.