change format of a array javascript - javascript

How can I change the format of the array? the idea is to place the array2 equal to the array1, I mean the format of square brackets and commas.
that is, change the ":" with "," and the {} with []
var array1=[["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]]
var array2=[{"Sep":687918},{"Nov":290709},{"Dic":9282},{"Ene":348529}]

The most appropriate way to do this is probably using the map() method. Using this, you're constructing a new array by manipulating each item of an original array. Learn more here.
var array2=[{"Sep":687918},{"Nov":290709},{"Dic":9282},{"Ene":348529}];
var array1 = array2.map(function (item) {
var key = Object.keys(item)[0];
var value = item[key];
return [key, value];
});
console.log(array1);
// returns [["Sep", 687918], ["Nov", 290709], ["Dic", 9282], ["Ene", 348529]]

This work for you?
var array1=[["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]];
var array2 = {};
array1.forEach(function(element){
array2[element[0]]=element[1];
});

"I mean the format of square brackets and commas"
Square brackets says, that it is an array, and array elements should be separated by commas. Actually, you want to convert the array of arrays to the array of objects. Here is short ES6 solution:
var array1 = [["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]];
var newArray = [];
array1.forEach(item => newArray.push({[item[0]]: item[1]}))
console.log(newArray)

You can do this by using the array .reduce method:
var array1=[["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]]
var array2 = array1.reduce((arr2, current) => {
arr2.push({[current[0]]: current[1]});
return arr2
}, []);
console.log(array2)

Related

Add array inside array in Javascript

How do I push array into a new Array.
For example
var arr = ['one','two','three'];
var newArr = [];
Now I want newArr[0] = ['one','two','three']
I have tried using push function but it pushes all the elements of arr into newArr. I want to push the entire arr as it is in newArr
var arr = ['one','two','three'];
var newArr = [];
newArr.push(arr); //<-- add entire original array as first key of new array
You can write:
newArr[0] = ['one','two','three'];
And this will work. Or use variable:
newArr[0] = arr;
Also, array methods push or unshift will the same way in your situation work:
newArr.push(arr);
Others have answered, so I guess your question is not really clear.
As you put your question, first and only element of newArray should be the arr array, then you use
newArr.push(arr);
as Mitya and Tiij7 said.
However, maybe you meant you want to join (concat) 2 arrays in a new array? Then you would use:
var arr3 = [].concat(arr, newArr);
or
var arr3 = [...arr, ...newArr];
Or you just wanted to clone the initial array? Then use
var newArr = [...arr];

Convert array with 5 items into array with 1 item

I have an array called 'xxx' with contains 5 items.
I would like to convert it in to a single array with the name newTableData[].
What is the best way to do this?
You can assign array with 5 elements to the zeroth element of second array
var newArray = [];
newArray[0] = existingArray;
var cars = ["Audi", "Volvo", "BMW", "Bentley", "Maruti"];
var newArray = [];
newArray[0] = cars;
console.log(newArray);
For flattening your initial array, you can just do
const flattenedArray = [].concat.apply([], oldArray);
const newArray = [flattenedArray];
If I'm right, the problem is that you have an Array of Arrays of TableItems. Just use a reduce and concat:
xxx.reduce((acc, arrayWithTableItem) => acc.concat(arrayWithTableItem), []);
This way you take advantage of the fact that concat flattens a single level down, so from this:
[[TableItem], ...[TableItem]]
you end up with
[TableItem, ...TableItem]
It's easy peas from there
[xxx.reduce((acc, x) => acc.concat(x), [])]
if you are using ES6+ you can use array destructuring ...
cont newTableData[0] = [...xxx];

How should i get array of array in javascript as a single value array?

If a have an array in javascript like:
[[2,3,4],"data","payload",[name1,name2,name3]]
how should I get all the values as a single array like
Result array should be like this :
[2,3,4,"data","payload",name1,name2,name3]
You can flatten it with .concat().
var data = [[2,3,4],"data","payload",["name1","name2","name3"]];
console.log([].concat(...data));
Any Array argument passed to .concat() will be flattened into the result.
This also uses the "spread syntax", which is only available in newer engines. Use .apply() for legacy support.
var data = [[2,3,4],"data","payload",["name1","name2","name3"]];
console.log(data.concat.apply([], data));
Use reduce() for this.
const array = [[2,3,4],"data","payload",["name1","name2","name3"]]
const flattenedArray = array.reduce((a, b) => a.concat(b), [])
console.log(flattenedArray)
MDN reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
You could use concat() to concatenate all the items in your main array into one big array, which I understand is what you're after :
var my2dArray = [[2,3,4],"data","payload",[name1,name2,name3]];
var my1dArray = [];
for(var i = 0; i < my2dArray.length; i++)
{
my1dArray = my1dArray.concat(my2dArray[i]);
}
console.log(my1dArray); // will be [2,3,4,"data","payload",name1,name2,name3]
You can use the concat():
var array = [
[2, 3, 4],
"data",
"payload",
['name1', 'name2', 'name3'],
]
var newArr = [].concat.apply([], array);
console.log(newArr);

How to collect / make new array by existing arrays label wise?

How to create new array from slicing the existing array by it's key?
for example my input is :
var array = [{"one":"1"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},
{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},
{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},
{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},
{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005"} ];
my output should be :
var outPutArray = [
{"one" : ["1","01","001","0001","00001"]},
{"two":["2","02","002","0002","00002"]},
{"three":["3","03","003","0003","00003"]},
{"four":["4","04","004","0004","00004"]},
{"five":["5","05","005","0005","00005"]}
]
is there any short and easy way to achieve this in javascript?
You can first create array and then use forEach() loop to add to that array and use thisArg param to check if object with same key already exists.
var array = [{"one":"1","abc":"xyz"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005","abc":"xya"} ];
var result = [];
array.forEach(function(e) {
var that = this;
Object.keys(e).forEach(function(key) {
if(!that[key]) that[key] = {[key]: []}, result.push(that[key])
that[key][key].push(e[key])
})
}, {})
console.log(result);
var outputArray=[array.reduce((obj,el)=>(Object.keys(el).forEach(key=>(obj[key]=obj[key]||[]).push(el[key])),obj),{})];
Reduce the Array to an Object,trough putting each Arrays object key to the Object as an Array that contains the value.
http://jsbin.com/leluyaseso/edit?console

Match two Arrays as Object of Array

I have two arrays and I need to make it as object of array
var arr1 = [1,2,3,4,5]
var arr2 = [a,b,c]
Is there any possibility to change the array to this format[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
Could someone help me?
Try this code:
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = arr2.reduce(function(obj, item) {
obj[item] = arr1.slice(); // or = arr1 to keep the reference
return obj;
}, {});
console.log(result); // {"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
You have 2 cases:
To create clones of the array use result[item] = arr1.slice();
To keep the reference to the same array use result[item] = arr1;
Check more about the reduce() method.
I am assuming you need a object like this
{"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
So you can do it like this.
var arr1 = [1,2,3,4,5]
var arr2 = ["a","b","c"];
var result={}
arr2.map(function(k){
result[k]=arr1;
})
console.log(result);
But here I am giving values of keys as arr1 reference so if arr1 will change value of keys in result will also change.
Is there any possibility to change the array to this
formate[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
This is neither an array format nor a valid JSON literal, so this format could only be a string.
Assuming that you are looking for a string in the format you have specified
var output = "[" + arr2.map(function(value){return value+",{" + arr1.join(",") + "}"}).join("],[") + "]";
Use forEach to iterate through List and get your desired result.
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = {} // Result: Object of Array
arr2.forEach(function(val, index) {
result[val] = arr1;
})
I hope this is easy to understand :)

Categories

Resources