A way to push array of objects into an array - javascript

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);

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);

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);

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])

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]);

Related

How to combine array within another array using javascript or jquery?

I have an array named arr and within that array, I have another array.My question is, how to combine this two array?
var arr=["1","2","[3,4]","5"]
My output should be like this:
1,2,3,4,5
Thanks in advance!
You could use spread syntax ... with map and JSON.parse methods.
var arr = ["1","2","[3,4]","5"]
var result = [].concat(...arr.map(e => JSON.parse(e)))
console.log(...result)
Considering that you have an actual array and not a string you can flatten like this
var arr=["1","2",["3","4"],"5"]
var flat = [].concat(...arr)
console.log(flat)
You can change it to string and further replace the square brackets using replace(/[\[|\]]/g,''):
var arr=["1","2","[3,4]","5"];
var res = arr.toString().replace(/[\[|\]]/g,'');
console.log(res);
If the question is how to flat an array like this [1,2,[3,4],5] or this [1,[2,[[3,4],5]]] into this[ 1, 2, 3, 4, 5 ] here a pretty general and short solution:
var arr = [1, [2, [[3, 4], 5]]];
var newArr = JSON.parse("[" + JSON.stringify(arr).replace(/\[|\]/g, "") + "]");
console.log(newArr)
Or .flat if browser supports it:
var arr = [1, 2, [3, 4, [5, 6]]];
arr.flat();
console.log(arr)

Javascript push an array to a 2-dim array

So i have 2 single dim arrays
array1 = [1,2,3];
array2 = [4,5,6];
And an empty 2-dim array
setArray = [[],[]];
How am i going to push the contents of the arrays to setArray so that it looks like this... considering we don't know the length of the single dim arrays?
setArray = [
[1,2,3],
[4,5,6]
];
I'm working on a project and my problem looks like this. Thank you.
if you just want to push contents of the two arrays in setArray you can do something like this:
Each element of setArray will have a reference to one of the arrays.
var array1 = [1,2,3], array2 = [4,5,6];
var setArray = [];
setArray.push(array1);
setArray.push(array2);
console.log(setArray);
array1 = [1,2,3]; array2 = [4,5,6];
setArray = [array1,array2];
console.log(setArray)
You can do it this way too.

how to push an element at index 0 of an array [duplicate]

This question already has answers here:
How to insert an item into an array at a specific index (JavaScript)
(28 answers)
Closed 6 years ago.
i have a situation like this,
i have 2 array1 as array1 = ["fruit","vegetables"];
and
array2 = [["apple","banana"],["tomato"]]; // index 0:represent fruit i,e (["apple","banana"]), index 1: vegetables i,e (["tomato"])
my question : how can i push item from array1 so as to make my array2 look like this
[["fruit","apple","banana"],["vegetables","tomato"]];
with that i can determine index:0 as category.
MY data structure is these 2 array array1 = ["fruit","vegetables"]; AND array2 = [["apple","banana"],["tomato"]];
if i'm able to get key value pair array that would good for me.
my sample data:
array1 = ["fruit","vegetables"];
array2 = [["apple","banana"],["tomato"]]; //expected output :[["fruit","apple","banana"],["vegetables","tomato"]];
Use Array#unshift method.
var array1 = ["fruit", "vegetables"],
array2 = [
["apple", "banana"],
["tomato"]
];
var array3 = array2.map(function(v, i) { // iterate over the array to generate the new array
var arr = v.slice(); // copy the array
arr.unshift(array1[i]) // insert element at beginning
return arr; /// return generated array
});
console.log(array3)
UPDATE : If you don't want to create a new array then you can avoid the copying part.
var array1 = ["fruit", "vegetables"],
array2 = [
["apple", "banana"],
["tomato"]
];
array2.forEach(function(v, i) { // iterate over the array
v.unshift(array1[i]) // insert element at beginning
});
console.log(array2)
With ES6 arrow function :
var array1 = ["fruit", "vegetables"],
array2 = [
["apple", "banana"],
["tomato"]
];
array2.forEach((v, i) => v.unshift(array1[i]));
console.log(array2)
Try this Array.map() and Array.unshift() .unshift() push the data into array [0]index position.
array1 = ["fruit","vegetables"];
array2 = [["apple","banana"],["tomato"]];
array2.map((a,i) => a.unshift(array1[i]))
console.log(array2)

Store result of array.sort in another variable

This seems like a simple question but I can't find much info on this.
var array1 = new Array(4, 3, 1, 2, 0, 5);
var array2 = array1;
array2.sort(function(a, b) {
return a - b;
})
Expected behavior: array2 is sorted and array1 is in the original order starting with 4.
Actual result: both arrays are sorted.
How can I sort array1 - while maintaining array1 and storing the results of the sort in array2? I thought that doing array2 = array1 would copy the variable, not reference it. However, in Firefox's console both arrays appear sorted.
That's becasue with var array2 = array1; you're making a new reference to the object, so any manipulation to array2 will affect array1, since the're basically the same object.
JS doesn't provide a propner clone function/method, so try this widely adopted workarround:
var array1 = new Array(4, 3, 1, 2, 0, 5);
var array2 = JSON.parse(JSON.stringify(array1));
array2.sort(function(a, b) {
return a - b;
});
Hope it helps :)
You can copy a array with slice method
var array1 = new Array(4, 3, 1, 2, 0, 5);
var array2 = array1.slice();

How to use array variable in array?

I have an array and I want to put same array and other array inside of the first array.
var arr=["a","b","c",arr,arr2];
var arr2=["a","b"];
var arr3=[];
arr3=arr[3];
When I print out arr, I can see
["a","b","c",,]
But if I print out arr3, The result is undefined.
How can I fix it?
You need to do this in the right order:
var arr1 = [];
var arr2 = [ "a", "b" ];
// Now arr1 and arr2 are defined so you can throw them into another array:
var arr3 = [ "a", "b", "c", arr1, arr2 ];
You've defined arr as part of itself - arr[3] is arr. But at the time, arr doesn't exist yet, so it comes out as undefined.

Categories

Resources