So I'm getting values and I want to put them into an array:
var values = {25,23,21}
var unit = {PCS,KG,PCS}
I want it to be like this when I put them in an array
array = {25:PCS,23:KG,21:PCS}
and group and add them depending on the unit so the final result will be something like this
totalval = {46:PCS,23:KG}
I can only put those values into separate arrays but I don't know how can I combine and group them..
https://jsfiddle.net/wyh5a2h2/
I went through reorganizing your code so it makes a bit of sense and came up with this: Hopefully it suits what you are attempting to do:
var items = [
{value: 25, unit: 'PCS'},
{value: 23, unit: 'KG'},
{value: 21, unit: 'PCS'},
]
var numPCS = 0, numKG = 0;
var result = [];
items.forEach(function(elem, index) {
if(elem.unit==='PCS') {
numPCS+=elem.value;
}
if(elem.unit==='KG') {
numKG+=elem.value;
}
});
result.push({value: numPCS, unit: 'PCS'});
result.push({value: numKG, unit: 'KG'});
console.log(result);
Here is the result:
var values = [25, 23, 21],
unit = ['PCS', 'KG', 'PCS'],
result = {},
tmpval = {},
totalval = {};
for (var i = 0; i < values.length; i++) {
result[values[i]] = unit[i];
tmpval[unit[i]] || (tmpval[unit[i]] = 0);
tmpval[unit[i]] += values[i];
}
for (var i in tmpval) {
totalval[tmpval[i]] = i;
}
// result: { '21': 'PCS', '23': 'KG', '25': 'PCS' }
// totalval: { '23': 'KG', '46': 'PCS' }
you will have to create objects first and then put them into an array
var obj1 = {
value: 25,
unit: "PCS"
};
...
var array = [ obj1, obj2, obj3, ... ];
then aggregate them accordingly
Related
I would like to know how to create object array based on max value in javascript,
based on max value how to create object as shown
for(var i = 0; i<=max;i++){
var result = [];
result.push({id: `${i}`, name: `s${i}`});
return result;
}
var max = 20;
var obj = [{id: 0, name: ""}]
Expected Output
result = [
{id: 1, name: "s1"},
{id: 2, name: "s2"},
{id: 3, name: "s3"},
..
..
{id: 20, name: "s20"}
]
Firstly, if you want to return a value you'll need a function. Then you'll have to take the initialization of the array out of the for loop, otherwise you'll be initializing it with every iteration. Then you can push the new objects to the array and finally you can return the newly populated array, like so:
const createObjectArray = (max) => {
var result = [];
for (var i = 0; i <= max; i++) {
result.push({ id: `${i}`, name: `s${i}` });
}
return result;
}
var max = 20;
let result = createObjectArray(max);
console.log(result);
I'd like to concat 2 arrays in JSON with key and value.
MyArray1 [ "Orange:10", "Orange:5", "Banana:20", "Apple:5" ]
MyArray2 [ "Orange:5", "Banana:10", "Apple:15" ]
MyJSON [
{"fruit": "Orange", "value": 15},
{"fruit": "Banana", "value": 20},
{"fruit": "Apple ", "value": 5},
],[
{"fruit": "Orange", "value": 5},
{"fruit": "Banana", "value": 10},
{"fruit": "Apple ", "value": 15},
]
]
I've tried this but I need a key and value and concat my 2 arrays :
MyArray1.forEach(function(val) {
var item = val.split(":");
var key = item[0];
var num = parseInt(item[1], 10);
if (MyArray1.hasOwnProperty(key)) {
MyArray1[key] += num;
} else {
MyArray1[key] = num;
}
});
As promised, here is a new version that sums up the values of the the same fruit Note that the values are integer which is more convenient for adding. Anyway if you absolutely want strings use arr[i].value=arr[i].value.toString() ;
Please give me a feedback.
var myArray1 = [ "Orange:10", "Orange:5", "Banana:20", "Apple:5" ];
var myArray2 = [ "Orange:5", "Banana:10", "Apple:15" ];
var myObjectArray1 = arrayToObjectArray(myArray1);
var myObjectArray2 = arrayToObjectArray(myArray2);
var myOnlyOneObjectArray= myObjectArray1.concat(myObjectArray2);
var myResult = mergeObjectArray(myOnlyOneObjectArray,"fruit","value")
console.log(myResult);
function arrayToObjectArray(arr){
// Map allows us to return a transformed row for each array row
var arr2 = arr.map(function(item) {
var items = item.split(":");
item = {};
item.fruit = items[0];
item.value = parseInt(items[1]);
return item;
});
return arr2;
}
function mergeObjectArray(arr,compareKey,addKey){
// Pay attention : we loop thru the same arr searching from end to start (i)
// and check if the same fruit already exist (second loop j from start to one row before i)
// that way we can sum any number of concated arrays and even dupes in the same original array
for(var i = arr.length-1; i >=0;i--){
for(var j = 0; j < arr.length -1;j++){ // Note that an objet property can be accessed also this way arr[i]["fruit"] == arr[i].fruit == arr[i][compareKey]
if((arr[i][compareKey]==arr[j][compareKey]) && (i!=j)){ // if the fruit (compare key) is the same (has been found)
arr[j][addKey]+=arr[i][addKey]; // we sum
arr.splice(i, 1); // we get rid of row (from end to start i, not to mess with the offset of the loop)
break;
}
}
}
return arr;
}
Here is a quick example :
I make a simple function just to transform the flat array into an array of objects and then I put the two resting arrays into another array
var myArray1 = [ "Orange:10", "Orange:5", "Banana:20", "Apple:5" ];
var myArray2 = [ "Orange:5", "Banana:10", "Apple:15" ];
var myArray1b = arrayToObjectArray(myArray1);
var myArray2b = arrayToObjectArray(myArray2);
var myResult = [myArray1b,myArray2b];
console.log(myResult);
function arrayToObjectArray(arr){
var arr2 = arr.map(function(item) {
var items = item.split(":");
item = {};
item.fruit = items[0];
item.value = items[1];
return item;
});
return arr2;
}
[NOTE: though similar to this stack question, my question differers significantly (IMO) due to the different structures of the initial variables. Mine is an array, the other questioner's is an object. My array contains nested objects/arrays, the latter of which contain name-value pairs whose values are, unlike the pairs in the other questioner's, not semantically identified.]
I have one big array (arr1) containing 24 objects. Each of the 24 objects contains one object, and one array of six further objects, like so:
var arr1 =
[
{'hour':1,'car':[{'audi':1377},{'bmw':716},{'ford':3819},{'mazda':67},{'toyota':11580},{'tesla':0}]},
{'hour':2,'car':[{'audi':1340},{'bmw':709},{'ford':3420},{'mazda':28},{'toyota':11583},{'tesla':0}]},
...etc, up to hour 24
];
As you can see, each of the 24 objects represents one hour's worth of data on car models and mileage. (What is NOT obvious is that the numeric value in each of the six objects represents miles.)
Now, I want to convert each object in arr1 into one array containing six objects, like below. So Hour 1's data in arr1 would convert to:
var arr2 = [{"car":"audi","miles":1377},{"car":"bmw","miles":716},{"car":"ford","miles":3819},{"car":"mazda","miles":67},{"car":"toyota","miles":11580},{"car":"tesla","miles":0}];
How can I do this? I have tried the following:
var hourx = 1;
var hour = arr1[hourx-1];
var car=hour.car;
for(var hourx1=0;hourx1<car.length;hourx1++){
var xx = car[hourx1];
var newobj = [];
for (var value in xx) {
var chartvar = newobj.push({car:value,miles:xx[value]});
var arr2 = newobj;
}
}
... but if I console.log(arr2); it only gives one array of one object.
I'm stumped. Anybody have an idea how I could accomplish this?
So you want to have an array of arrays as a final result?
var arr1 = [
{'hour':1,'car':[{'audi':1377},{'bmw':716},{'ford':3819},{'mazda':67},{'toyota':11580},{'tesla':0}]},
{'hour':2,'car':[{'audi':1340},{'bmw':709},{'ford':3420},{'mazda':28},{'toyota':11583},{'tesla':0}]}
];
var arr2 = arr1.map(function(hour){
return hour.car.map(function(car){
var carName = Object.keys(car)[0];
return {
"car": carName,
"miles": car[carName]
}
})
})
https://jsfiddle.net/1jjzeeyz/
Try using .map() , Object.keys()
var arr1 = [{
'hour': 1,
'car': [{
'audi': 1377
}, {
'bmw': 716
}, {
'ford': 3819
}, {
'mazda': 67
}, {
'toyota': 11580
}, {
'tesla': 0
}]
}, {
'hour': 2,
'car': [{
'audi': 1340
}, {
'bmw': 709
}, {
'ford': 3420
}, {
'mazda': 28
}, {
'toyota': 11583
}, {
'tesla': 0
}]
}];
var hours = arr1.map(function(cars, index) {
var carNames = Object.keys(cars.car);
var names = carNames.map(function(c) {
var name = Object.keys(cars.car[c])[0];
var res = {};
res["car"] = name;
res["miles"] = cars.car[c][name];
return res
})
return names
})
console.log(hours)
You would have to iterate over the array. Get the first property (let's hope it stays this way). Then get it value. Then create an object and add it to the array. See fiddle here
var arr1 =
[
{'hour':1,'car':[{'audi':1377},{'bmw':716},{'ford':3819},{'mazda':67},{'toyota':11580},{'tesla':0}]},
{'hour':2,'car':[{'audi':1340},{'bmw':709},{'ford':3420},{'mazda':28},{'toyota':11583},{'tesla':0}]},
];
var arr = [];
for (var i = 0; i< arr1[0].car.length; i++){
var car = arr1[0].car[i];
var key = Object.keys(car)[0];
arr.push({
car: key,
miles: car[key]
});
}
a combination of reduce and map will help. /example:
var
arr1 =[
{'hour':1,'car':[{'audi':1377},{'bmw':716},{'ford':3819},{'mazda':67},{'toyota':11580},{'tesla':0}]},
{'hour':2,'car':[{'audi':1340},{'bmw':709},{'ford':3420},{'mazda':28},{'toyota':11583},{'tesla':0}]}
],
arr2 = arr1.reduce(function (collector, item) {
collector.push(item.car.map(function (car/*, idx, list*/) {
var
make = Object.keys(car)[0]
;
return {
"car" : make,
"miles" : car[make]
}
}));
return collector;
}, [])
;
console.log("arr2 : ", arr2);
If I start with the following:
var people = [
{id: 9, name: 'Bob', age: 14},
{id: 11, name: 'Joe', age: 15},
{id: 12, name: 'Ash', age: 24}]
What I am trying to get using underscore.js or lodash is a single hash/object with an array of all the values from the collection:
{
id: [9, 11, 12],
name: ['Bob', 'Joe', 'Ash'],
age: [14, 15, 24]
}
Any thoughts?
An answer in straightforward JavaScript code (no libraries):
var result = {};
for (var i = 0; i < people.length; i++) {
var item = people[i];
for (var key in item) {
if (!(key in result))
result[key] = [];
result[key].push(item[key]);
}
}
Here's an alternate plain javascript answer. It's basically the same as Nayuki's but possibly a bit more expressive.
var obj = {};
people.forEach(function(person){
for(prop in person) {
obj[prop] = obj[prop] || [];
obj[prop].push(person[prop]);
}
});
using array.map():
var acc = {};
for (k in people[0]) {
acc[k] = people.map(function (x) {
return x[k]
})
}
fiddle
this solution assumes that all the needed keys will be found in people[0] ...
EDIT:
this is a more extreme version that should catch the keys along the way:
people.reduce(function (ac, item) {
for (k in item) {
if(!ac[k])
ac[k] =[];
ac[k].push(item[k])
}
return ac
}, {})
fiddle2
An alternative that uses Object.keys, Array.prototype.reduce and Array.prototype.map methods:
var res = Object.keys(people[0]).reduce(function(ret, key) {
ret[key] = people.map(function(el) { return el[key]; });
return ret;
}, {});
I don't know javascript much.
But one approach would be to create three arrays, let's say
var id = [];
var name = [];
var age = [];
Then loop through the people array
for(var i=0; i<people.length; i++){
id.push(people[i].id);
name.push(people[i].name);
age.push(people[i].age);
}
Now you have three arrays with respective ids, names and ages
The last step would be to create your final object
var object = {
id:id
name:name
age:age
};
I am looking for a solution, to push/convert array items into a object back, without using keys?
function pleaseBuy(){
var args = arguments;
for(var i = 0; i < arguments[0].length; ++i) {
args += args[i];
};
};
function getList(){
return ["pepsi","cola","7up"];
}
var list = ({ favorite: "drpepper"}, getList())
pleaseBuy(list)
Expected result:
args = ({ favorite: "drpepper"}, "pepsi", "cola", "7up")
No need for the pleaseBuy function, I'd say:
function getList(){
return ["pepsi","cola","7up"];
}
var list = getList().concat( { favorite: "drpepper" } );
// ^ NB should be :
// or favorite first
var list = [{ favorite: "drpepper" }].concat(getList());
/*
list now contains:
['pepsi, 'cola','7up',{ favorite: "drpepper" }]
*/
An object allways contains key-value pairs. If you want to convert an array to an object, you'll thus have to assign keys and values. For example:
var arr = [1,2,3,4,'some'], arr2Obj = {};
for (var i=0;i<arr.length;i=i+1){
arr2Obj[arr[i]] = i;
}
/*
arr2Obj now contains:
{
1: 0,
2: 1,
3: 2,
4: 3,
some: 4
}
*/
Other example:
var arr = [1,2,3,4,'some'], arr2Numbers = {};
for (var i=0;i<arr.length;i=i+1){
arr2Numbers[arr[i]] = !isNaN(Number(arr[i]));
}
/*
arr2Numbers now contains:
{
1: true,
2: true,
3: true,
4: true,
some: false
}
*/
Do you mean the javascript push function?
Use .unshift() docs to prepend to an array.
var list = getList();
list.unshift( { favorite="drpepper"});
// [{ favorite="drpepper"}, "pepsi", "cola", "7up"]
Demo at http://jsfiddle.net/Ds9y5/
Try this:
var array = ["pepsi","cola","7up"];
array.push({ favorite: "drpepper"});
Or
var array2 = ["pepsi","cola","7up"];
var array = [{favorite: "drpepper"}];
for(var ctr = 0 ; ctr < array2.length ; ctr++){
array.push(array2[ctr]);
}
var s = getList();
s.unshift({ favorite : "drpepper"}); // at the first place in array
s.push({ favorite : "drpepper"}); // at the last place in array
alert(s);
JavaScript push() Method
JavaScript unshift() Method