0

Here is the array of objects that is to be push to an array

[{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}]

How to achieve this array below from the above

"array": [
[
  [
    11,
    21
  ],
  [
    31,
    41
  ],
  
  [
    10,
    20
  ],
  [     
    11,  //first object again
    21
  ]  
]
]

Used array map to push elements but couldn't figure out a way to push the first object again

var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];

var array2 = [array1.map(item=>[item.a, item.b])];

console.log(array2);

4 Answers 4

1

You can do this,

var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];
array1.push(array1[0])

var array2 = [array1.map(item=>[item.a, item.b])];

console.log(array2);

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

Comments

1

I agree with slappy's answer, but no need to apply slice

const arr = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];
const arr2 = [arr.map(item=>[item.a, item.b])];
arr2.push(arr2[0][0]);

1 Comment

If the items in arr2 will be mutated in the future, then mutating the first item would also alter the last, because a copy is not made. If not, then a .slice() is unnecessary, but I'd probably still do it.
0

You just add another line of code that inserts that first index.

var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];

var array2 = [array1.map(item=>[item.a, item.b])];
array2[0].push([array1[0].a, array1[0].b]);

console.log(array2);

Do you need the double array on the outside though?

Anyway, another way would be to just copy the first array you originally pushed.

var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];

var array2 = [array1.map(item=>[item.a, item.b])];
array2[0].push(array2[0][0].slice());

console.log(array2);

And you can also make your .map() a little different using Object.values:

var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];

var array2 = [array1.map(Object.values)];
array2[0].push(array2[0][0].slice());

console.log(array2);

Comments

0

This can be done my manually pushing the first element again after you've done the mapping.

The unshift() method can be used to push to the front of array.

var array2 = [array1.map(item=>[item.a, item.b])];
array2.unshift([array1[0].a, array1[0].b])

3 Comments

You need to push to array2[0]
@slappy Edited, I meant to say unshift
You don't want unshift because he wants it at the end. But take a close look at the OP's result. He has [[ [...], [...], [...] ]]

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.