I have written down my first JavaScript code to do some dynamic rendering in a webpage:
var c_names = ["Canada", "USA", "israel"]
var c_ids = [1, 2, 3]
var c_domaain = ["www.canada.com", "www.usa.com", "www.israel.com"]
var data_1 = []
var C_data = [
['Country', 'ids', 'Domain']
]
var x = 1
for (i = 0; i == 3; i++) {
var x = x + 1
data_1.push(c_name[x], c_ids[x], c_domain[x])
for (i = 0; i < c_name.length; i++) {
C_data.push(data_1)
}
}
console.log(C_data)
I'm expecting this output:
data = [ ['Country', 'ids', 'Domain'],
['USA', 1, 'www.usa.com'],
['Canada', 2, 'www.usa.com'],
['Israel', 3, 'www.usa.com'],
]
Iterate over one of the arrays and then append the respective items.
var names = ["Canada", "USA", "israel"]
var ids = [1, 2, 3]
var domains = ["www.canada.com", "www.usa.com", "www.israel.com"]
var data = [
["Country", "ID", "Domain"]
]
names.forEach ((name, idx) => {
data.push ([ name, ids [idx], domains [idx]]);
});
console.log(data)
You could take the array in one array and iterate the outer and the the inner array while respecting the index.
var c_names = ["Canada", "USA", "israel"],
c_ids = [1, 2, 3],
c_domaain = ["www.canada.com", "www.usa.com", "www.israel.com"],
c_data = ['Country', 'ids', 'Domain'],
result = [c_names, c_ids, c_data].reduce(function (r, a) {
a.forEach(function (b, i) {
r[i] = r[i] || [];
r[i].push(b);
});
return r;
}, []);
result.unshift(c_data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
var c_names = ["Canada", "USA", "israel"]
var c_ids = [1, 2, 3]
var c_domaain = ["www.canada.com", "www.usa.com", "www.israel.com"]
var C_data = [
['Country', 'ids', 'Domain']
]
var i = -1;
while ( c_names[++i] ) {
C_data.push( [ c_names[i], c_ids[i], c_domaain[i]] );
}
console.log(C_data)
var c_names = ["Canada","USA","israel" ];
var c_ids = [1,2,3];
var c_domaain = ["www.canada.com","www.usa.com","www.israel.com"];
var data_1 = [];
var C_data = ['Country', 'ids', 'Domain'];
var x = 1;
for(var i = 0; i < c_names.length; i++){
data_1.push(new Array(C_data[i], c_names[i], c_domaain[i]));
};
console.log(data_1);
This is the output of your code which is wrong:
[ [ "Country", "ids","Domain"],
[ "Canada", 1, "Country"],
[ "USA", 2, "ids" ],
[ "israel", 3, "Domain"]
]
Related
I have a array of JSON objects defined as follow:
[
{
key : "test1",
data : {
"Mercedes" : {
"ClassA" : [1, 2],
"ClassB" : [1]
},
"Benz" : {
"ClassA" : [1]]
}
}
},
{
key : "test2",
data : {
"Mercedes" : {
"ClassA" : [1, 2, 3],
"ClassB" : [1]
},
"Toty" : {
"ClassA" : [1]]
}
}
},...
]
I would like to retrieve 3 distincts arrays:
One containing the name of distinct names that exist in all objects : result = ["Mercedes", "Benz", "Toty"]
One containing all distinct values of type: type = ["ClassA", "ClassB"]
One containing all distinct values of numbers : numbers = ["1", "2", "3"]
How can i retrieve these 3 arrays without needed to right multiple loops ?
This is not perfect, could be done in cleaner more "JS-y" ways, but here ya go
var someArray = ...; // your input array
var uniqueCars = new Set();
var uniqueClasses = new Set();
for (var i = 0; i < someArray.length; i++) {
// iterate through all prop names
for (var carProp in someArray[i].data) {
uniqueCars.add(carProp);
for (var classProp in someArray[i].data[carProp]) {
uniqueClasses.add(classProp);
// Too lazy to do the last one, hopefully you can figure it out
}
}
}
var finalCars = Array.from(uniqueCars);
var finalClasses = Array.from(uniqueClasses);
// do the 3rd one you asked for
Check out reduce - one of the many possible ways you can do it.
var data = [{
key: "test1",
data: {
"Mercedes": {
"ClassA": [1, 2],
"ClassB": [1]
},
"Benz": {
"ClassA": [1]
}
}
},
{
key: "test2",
data: {
"Mercedes": {
"ClassA": [1, 2, 3],
"ClassB": [1]
},
"Toty": {
"ClassA": [1]
}
}
}
];
var thing = data.reduce((acc, itm) => {
for (var type in itm.data) {
if (acc.types.indexOf(type) === -1) acc.types.push(type);
for (var cls in itm.data[type]) {
if (acc.classes.indexOf(cls) === -1) acc.classes.push(cls);
for (var i = itm.data[type][cls].length; i--;)
if (acc.numbers.indexOf(itm.data[type][cls][i]) === -1)
acc.numbers.push(itm.data[type][cls][i]);
}
}
return acc;
}, {
types: [],
numbers: [],
classes: []
});
console.log('Unique Types', thing.types);
console.log('Unique Numbers', thing.numbers);
console.log('Unique Classes', thing.classes);
This is just a proof of concept, but I think it can be made a recursive function and be more elegant.
let arr = [{ key: "test1", data: { "Mercedes": { "ClassA": [1, 2], "ClassB": [1] }, "Benz": { "ClassA": [1] } } }, { key: "test2", data: { "Mercedes": { "ClassA": [1, 2, 3], "ClassB": [1] }, "Toty": { "ClassA": [1] } } }],
flatten = (a, b) => [...a, ...b],
allUnq = a => [...new Set(a.reduce(flatten))],
data = arr.map(o => o.data),
vals = d => d.map(Object.values),
keys = d => d.map(Object.keys),
arr1 = allUnq(keys(data)),
arr2 = allUnq(vals(data).map(keys).map(allUnq)),
arr3 = allUnq(allUnq(vals(allUnq(vals(data)))));
console.log(arr1);
console.log(arr2);
console.log(arr3);
.as-console-wrapper {max-height: 100% !important;top: 0;}
I am with some doubts about iterate into a JS Object and some array functions in JavaScript. Let's say I have these variables:
var json1 = "[{"id": 1, "name":"x"}, {"id": 2, "name":"y"}]";
var json2 = "[{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}]";
How can I make a variable with only the IDs in a array
var ids1 = json1.ids (would be 1,2)
var ids2 = json2.ids (would be 1,2,3)
and make another variable only with the IDs that are different
var idsdiff = diff(ids1, ids2) (would be 3)
var json1 = [{"id":1,"name":"x"}, {"id":2,"name":"y"}],
json2 = [{"id":1,"name":"x"}, {"id":2,"name":"y"}, {"id":3,"name":"z"}],
result1 = json1.map(function (a) { return a.id; }),
result2 = json2.map(function (a) { return a.id; });
var diffs = result2.filter(function (item) {
return result1.indexOf(item) < 0;
});
console.log(result1);
console.log(result2);
console.log(diffs);
Note indexOf and filter and map are not available in iE before iE9.
UPDATE: as per #alexandru-Ionutmihai's comment, filter will fail on [1,2,4] and [1,2,3]
This code seems better:
var json1 = [{"id":1,"name":"x"}, {"id":2,"name":"y"}],
json2 = [{"id":1,"name":"x"}, {"id":2,"name":"y"}, {"id":3,"name":"z"}],
result1 = json1.map(function (a) { return a.id; }),
result2 = json2.map(function (a) { return a.id; });
//as per #alexandru-Ionutmihai this is inaccurate for [1,2,4] and [1,2,3]
/*var diffs = result2.filter(function (item) {
return result1.indexOf(item) < 0;
});*/
//here's a workaround
function arr_diff(a, b) {
var i,
la = a.length,
lb = b.length,
res = [];
if (!la)
return b;
else if (!lb)
return a;
for (i = 0; i < la; i++) {
if (b.indexOf(a[i]) === -1)
res.push(a[i]);
}
for (i = 0; i < lb; i++) {
if (a.indexOf(b[i]) === -1) res.push(b[i]);
}
return res;
}
var diffs = arr_diff(result1, result2),
testDiff = arr_diff([1, 2, 4], [1, 2, 3]);
console.log(result1);
console.log(result2);
console.log(diffs);
console.log(testDiff);
arr_diff credit to #Nomaed's comment on this question's answer.
You could use a hash table for the id and make the difference with the value. Then render the result by filtering.
function getId(a) { return a.id; }
var obj1 = JSON.parse('[{"id": 1, "name":"x"}, {"id": 2, "name":"y"}]');
var obj2 = JSON.parse('[{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}]');
var ids1 = obj1.map(getId);
var ids2 = obj2.map(getId);
var hash = {};
ids1.forEach(function (a) {
hash[a] = 1;
});
ids2.forEach(function (a) {
hash[a] = (hash[a] || 0) - 1;
});
var difference = Object.keys(hash).filter(function (a) { return hash[a]; }).map(Number);
console.log(ids1);
console.log(ids2);
console.log(hash);
console.log(difference);
.as-console-wrapper { max-height: 100% !important; top: 0; }
With lodash, you could use _.xor for a symmetric difference.
var ids1 = [1, 2],
ids2 = [1, 2, 3];
console.log(_.xor(ids1, ids2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
If those JSONs are not parsed, you need one extra step before:
json1 = JSON.parse(json1);
If not, please use this code:
var json1 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}];
var json2 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}];
// extra steps, if necessary
// json1 = JSON.parse(json1);
// json2 = JSON.parse(json2);
function returnID (item) {
return item.id;
};
json1 = json1.map(returnID);
json2 = json2.map(returnID);
var diff = json2.filter(function (item) {
return json1.indexOf(item) < 0;
});
console.log(diff);
You can use map method in combination with filter method.
var json1 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}];
var json2 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}];
var j1=json1.map((x)=>{return x.id});
var j2=json2.map((x)=>{return x.id});
var diff = j2.filter(function(el){
return j1.indexOf(el)==-1;
}).concat(j1.filter(function(el){
return j2.indexOf(el)==-1;
}));
console.log(diff);
Also, this code works if both json arrays contains IDs that are different.
var json1 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 4, "name":"y"}, {"id": 5, "name":"y"}];
var json2 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}];
var j1=json1.map((x)=>{return x.id});
var j2=json2.map((x)=>{return x.id});
var diff = j2.filter(function(el){
return j1.indexOf(el)==-1;
}).concat(j1.filter(function(el){
return j2.indexOf(el)==-1;
}));
console.log(diff);
To get the arrays filled with only the id properties of each object, simple do...
var ids1 = json1.map(x => x.id)
var ids2 = json2.map(x => x.id)
If you are using ES6, or a version transpiler, you can use the spread operator to get the difference between the two like:
var diff = [...id1.filter(x => id2.indexOf(x) == -1), ...id2.filter(x => id1.indexOf(x) == -1)]
var json1 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}];
var json2 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}];
var ids1 = json1.map(x => x.id);
var ids2 = json2.map(x => x.id);
var diff = [...ids1.filter(x => ids2.indexOf(x) == -1), ...ids2.filter(x => ids1.indexOf(x) == -1)];
console.log(diff);
Here I let you two functions to get the results that you want:
First function (getIds):
var json1 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}];
var json2 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}];
function getIds (array) {
return array.map(function (obj) {
return obj.id;
});
}
console.log(getIds(json1));
console.log(getIds(json2));
Second function (getDiff)
var json1 = [1, 2, 4, 5];
var json2 = [1, 2, 3];
function getDiff (array1, array2) {
return array1.concat(array2).filter(function (id, index, arr) {
return arr.indexOf(id) === arr.lastIndexOf(id);
});
}
console.log(getDiff(json1, json2));
Using Array of array to object - javascript and Convert an array to an array of objects as a guide I tried to write a function that results in
taking this array of array list:
var list = [['name', 'Sparky'], ['breed', 'lab'], ['age', 4]];
and converting it into this:
{
name : 'Sparky'
breed : 'lab',
age : 4
}
However, when I run the code below:
var list = [
['name', 'Sparky'],
['breed', 'lab'],
['age', 4]
];
function toObjects(data) {
var keys = data.shift(),
i = 0,
k = 0,
obj = null,
output = [];
for (i = 0; i < data.length; i++) {
obj = {};
for (k = 0; k < keys.length; k++) {
obj[keys[k]] = data[i][k];
}
output.push(obj);
}
return output;
}
var data = [
['name', 'Sparky'],
['breed', 'lab'],
['age', 4]
];
console.log(toObjects(data))
I get this:
console.log(toObjects(data)); //=>
[ { name: 'breed', Sparky: 'lab' },{ name: 'age', Sparky: 4 } ]
but I need the output to not have an extra array [ ] and to also be listed single file like this:
{
name : 'Sparky'
breed : 'lab',
age : 4
}
Any advice? Please and thank you!
I would use Array.prototype.reduce to perform your transformation as well as argument destructing. Take a look, the code is pretty simple :)
let list = [
['name', 'Sparky'],
['breed', 'lab'],
['age', 4]
];
function toObjects(data) {
// reduce iterates through every element in the `data` array
// and accumulates it into the object
let initialValue = {};
return data.reduce((obj, [key, value]) => {
obj[key] = value;
return obj;
}, initialValue); // this could be in-lined with `{}`
}
var data = [
['name', 'Sparky'],
['breed', 'lab'],
['age', 4]
];
console.log(toObjects(list))
You can use map function to achieve this
var list = [['name', 'Sparky'], ['breed', 'lab'], ['age', 4]];
var newObj = new Object();
list.forEach(function (arr) {
newObj[arr[0]] = arr[1];
});
console.log(newObj)
I have an 'item' object in JavaScript, and the item can have settings like
color, size, etc.
I need to get all possible combinations in an array.
So lets say we have an item that looks like this:
var newItem = {
name: 'new item',
Settings: [
{name: 'color', values: ['green', 'blue', 'red']},
{name: 'size', values: ['15', '18', '22']},
{name: 'gender',values: ['male', 'female']}
]
};
I need to somehow get this:
[
[{SettingName:'color',value:'green'},{SettingName:'size',value:'15'},{SettingName:'gender',value:'male'}],
[{SettingName:'color',value:'blue'},{SettingName:'size',value:'15'},{SettingName:'gender',value:'male'}],
[{SettingName:'color',value:'red'},{SettingName:'size',value:'15'},{SettingName:'gender',value:'male'}],
[{SettingName:'color',value:'green'},{SettingName:'size',value:'18'},{SettingName:'gender',value:'male'}],
[{SettingName:'color',value:'blue'},{SettingName:'size',value:'18'},{SettingName:'gender',value:'male'}],
[{SettingName:'color',value:'red'},{SettingName:'size',value:'18'},{SettingName:'gender',value:'male'}],
[{SettingName:'color',value:'green'},{SettingName:'size',value:'22'},{SettingName:'gender',value:'male'}],
[{SettingName:'color',value:'blue'},{SettingName:'size',value:'22'},{SettingName:'gender',value:'male'}],
[{SettingName:'color',value:'red'},{SettingName:'size',value:'22'},{SettingName:'gender',value:'male'}],
[{SettingName:'color',value:'green'},{SettingName:'size',value:'15'},{SettingName:'gender',value:'female'}],
[{SettingName:'color',value:'blue'},{SettingName:'size',value:'15'},{SettingName:'gender',value:'female'}],
[{SettingName:'color',value:'red'},{SettingName:'size',value:'15'},{SettingName:'gender',value:'female'}],
[{SettingName:'color',value:'green'},{SettingName:'size',value:'18'},{SettingName:'gender',value:'female'}],
[{SettingName:'color',value:'blue'},{SettingName:'size',value:'18'},{SettingName:'gender',value:'female'}],
[{SettingName:'color',value:'red'},{SettingName:'size',value:'18'},{SettingName:'gender',value:'female'}],
[{SettingName:'color',value:'green'},{SettingName:'size',value:'22'},{SettingName:'gender',value:'female'}],
[{SettingName:'color',value:'blue'},{SettingName:'size',value:'22'},{SettingName:'gender',value:'female'}],
[{SettingName:'color',value:'red'},{SettingName:'size',value:'22'},{SettingName:'gender',value:'female'}]
]
This can be a good interview question.
See JS Bin for running example.
getAllPermutations(newItem);
function getAllPermutations(item) {
var permutations = [];
getAllPermutations0(item, permutations, []);
console.log(permutations);
}
function getAllPermutations0(item, permutations, array) {
if (array && array.length === item.Settings.length) {
permutations.push(array.slice()); // The slice clone the array
return;
}
var index = array.length;
var setting = item.Settings[index];
for (var i = 0; i < setting.values.length; i++) {
if (index === 0)
array = [];
var currValue = setting.values[i];
array.push({
SettingName: setting.name,
value: currValue
});
getAllPermutations0(item, permutations, array);
array.pop(); // pop the old one first
}
}
Here is a none recursive solution. It takes an empty or existing settings "matrix" and a values array, and return a new matrix as a combination of existing matrix content cloned for each new value, appended with pairs of new value setting items.
[A] -> [1,2] gives [A][1][A][2]
[A][1][A][2] -> [X,Y] gives [A][1][X][A][2][Y][A][2][X][A][1][Y]
and so on
function processSettings(settings, name, values) {
if (settings.length == 0) {
values.forEach(function(value) {
settings.push( [{ SettingName: name, value: value }] )
})
} else {
var oldSettings = JSON.parse(JSON.stringify(settings)), settings = [], temp, i = 0
for (i; i<values.length; i++) {
temp = JSON.parse(JSON.stringify(oldSettings))
temp.forEach(function(setting) {
setting.push( { SettingName: name, value: values[i] } )
settings.push(setting)
})
}
}
return settings
}
You can now create the desired settings literal this way :
var settings = []
for (var i=0; i<newItem.Settings.length; i++) {
var item = newItem.Settings[i]
settings = processSettings(settings, item.name, item.values)
}
demo -> http://jsfiddle.net/b4ck98mf/
The above produces this :
[
[{"SettingName":"color","value":"green"},{"SettingName":"size","value":"15"},{"SettingName":"gender","value":"male"}],
[{"SettingName":"color","value":"blue"},{"SettingName":"size","value":"15"},{"SettingName":"gender","value":"male"}],
[{"SettingName":"color","value":"red"},{"SettingName":"size","value":"15"},{"SettingName":"gender","value":"male"}],
[{"SettingName":"color","value":"green"},{"SettingName":"size","value":"18"},{"SettingName":"gender","value":"male"}],
[{"SettingName":"color","value":"blue"},{"SettingName":"size","value":"18"},{"SettingName":"gender","value":"male"}],
[{"SettingName":"color","value":"red"},{"SettingName":"size","value":"18"},{"SettingName":"gender","value":"male"}],
[{"SettingName":"color","value":"green"},{"SettingName":"size","value":"22"},{"SettingName":"gender","value":"male"}],
[{"SettingName":"color","value":"blue"},{"SettingName":"size","value":"22"},{"SettingName":"gender","value":"male"}],
[{"SettingName":"color","value":"red"},{"SettingName":"size","value":"22"},{"SettingName":"gender","value":"male"}],
[{"SettingName":"color","value":"green"},{"SettingName":"size","value":"15"},{"SettingName":"gender","value":"female"}],
[{"SettingName":"color","value":"blue"},{"SettingName":"size","value":"15"},{"SettingName":"gender","value":"female"}],
[{"SettingName":"color","value":"red"},{"SettingName":"size","value":"15"},{"SettingName":"gender","value":"female"}],
[{"SettingName":"color","value":"green"},{"SettingName":"size","value":"18"},{"SettingName":"gender","value":"female"}],
[{"SettingName":"color","value":"blue"},{"SettingName":"size","value":"18"},{"SettingName":"gender","value":"female"}],
[{"SettingName":"color","value":"red"},{"SettingName":"size","value":"18"},{"SettingName":"gender","value":"female"}],
[{"SettingName":"color","value":"green"},{"SettingName":"size","value":"22"},{"SettingName":"gender","value":"female"}],
[{"SettingName":"color","value":"blue"},{"SettingName":"size","value":"22"},{"SettingName":"gender","value":"female"}],
[{"SettingName":"color","value":"red"},{"SettingName":"size","value":"22"},{"SettingName":"gender","value":"female"}]
]
You can use Array.prototype.map(), for loop, while loop, Array.prototype.concat(). Iterate gender values; select each of color, size value in succession beginning at index 0 of either; iterating the furthest adjacent array from current gender, increment the index of the closest adjacent array; merge the resulting two gender arrays to form a single array containing all combinations of gender, color, size
var colors = newItem.Settings[0].values;
var sizes = newItem.Settings[1].values;
var gen = newItem.Settings[2].values;
var i = sizes.length;
var res = [].concat.apply([], gen.map(function(value, key) {
var next = -1;
var arr = [];
for (var curr = 0; curr < i; curr++) {
while (next < i - 1) {
arr.push([{
SettingName: "gender",
value: value
}, {
SettingName: "size",
value: sizes[curr]
}, {
SettingName: "color",
value: colors[++next]
}])
}
next = -1;
}
return arr
}))
var newItem = {
"name": "new item",
"Settings": [{
"name": "color",
"values": [
"green",
"blue",
"red"
]
}, {
"name": "size",
"values": [
"15",
"18",
"22"
]
}, {
"name": "gender",
"values": [
"male",
"female"
]
}]
}
var colors = newItem.Settings[0].values;
var sizes = newItem.Settings[1].values;
var gen = newItem.Settings[2].values;
var i = sizes.length;
var res = [].concat.apply([], gen.map(function(value, key) {
var next = -1;
var arr = [];
for (var curr = 0; curr < i; curr++) {
while (next < i - 1) {
arr.push([{
SettingName: "gender",
value: value
}, {
SettingName: "size",
value: sizes[curr]
}, {
SettingName: "color",
value: colors[++next]
}])
}
next = -1;
}
return arr
}))
document.querySelector("pre").textContent = JSON.stringify(res, null, 2)
<pre></pre>
plnkr http://plnkr.co/edit/C2fOJpfwOrlBwHLQ2izh?p=preview
An approach using Array.prototype.reduce(), Array.prototype.sort(), Object.keys(), for loop, while loop
var newItem = {
name: 'new item',
Settings: [
{
name: 'color',
values: ['green', 'blue', 'red']
},
{
name: 'size',
values: ['15', '18', '22']
},
{
name: 'gender',
values: ['male', 'female']
}
]
};
var props = ["SettingName", "value"];
var settings = newItem.Settings;
function p(settings, props) {
var data = settings.reduce(function(res, setting, index) {
var name = setting.name;
var obj = {};
obj[name] = setting.values;
res.push(obj);
return res.length < index ? res : res.sort(function(a, b) {
return a[Object.keys(a)[0]].length - b[Object.keys(b)[0]].length
})
}, []);
var key = data.splice(0, 1)[0];
return [].concat.apply([], key[Object.keys(key)].map(function(value, index) {
return data.reduce(function(v, k) {
var keys = [v, k].map(function(obj) {
return Object.keys(obj)[0]
});
var i = Math.max.apply(Math, [v[keys[0]].length, k[keys[1]].length]);
var next = -1;
var arr = [];
for (var curr = 0; curr < i; curr++) {
while (next < i - 1) {
var a = {};
a[props[0]] = keys[0];
a[props[1]] = v[keys[0]][++next];
var b = {};
b[props[0]] = keys[1];
b[props[1]] = k[keys[1]][next];
var c = {};
c[props[0]] = Object.keys(key)[0];
c[props[1]] = value;
arr.push([a, b, c]);
};
next = -1;
}
return arr
});
}));
}
document.querySelector("pre").textContent = JSON.stringify(
p(settings, props), null, 2
);
<pre></pre>
Split array of objects into new array or objects based on age value in Javascript
var items = [
{name:"Foo", age:16, color:"w"},
{name:"Bar", age:18, color:"b"},
{name:"foo", age:16, color:"w"},
{name:"bar", age:18, color:"w"},
{name:"foobar", age:18, color:"b"},
{name:"barfoo", age:20, color:"w"}
];
How can I return a list like:
var items = [
{age:16,name:"Foo"|"foo",gender:"w"|"w"},
{age:18,name:"Bar"|"bar"|"foobar",gender:"b"|"w"|"b"},
{age:20,name:"barfoo",gender:"w"}
];
I have worked but i got output with 'undefined' in name. Below is my code.
var data = [{age: 21,name: "Walter",color: "black"},{age: 25,name: "sentinel",color: "black"
},{age: 21,name: "Micah",color: "purple"},{age: 25,name: "mike",color: "black"},{age: 21,name: "Danny",color: "white"},{age: 25,name: "mike",color: "black"}];
var obj=data;
var arrayobj = obj.length;
var i, row, arr = obj, ss = {};
for (i = 0; i < arr.length; i++) {
row = arr[i];
ss[row.age] = ss[row.age] || {count: 0};
if (ss[row.age][row.age] === undefined) {
ss[row.age][row.name] = row.name;
ss[row.age]['name']+=row.name+'|';
ss[row.age]['color']+=row.color+'|';
ss[row.age]['count'] += 1;
}
}
console.table(ss);
I'm assuming you want to group the items by their age. Here is one way:
(fiddle)
items.reduce(function(buckets,item){
if(!buckets[item.age]) buckets[item.age] = [];
buckets[item.age].push(item);
return buckets;
},{});
Let's explain:
For each item, if we don't already have a 'bucket' for it, create a new empty one
Add it to the bucket
return the new updated bucket list.
The method returns an object with 3 properties: 16,18 and 20, each containing the objects with that age.
This will work. The output is in different format than one provided by exebook .
Please check and confirm. Here's a fiddle....
** UX Manager
var buckets = [];
for (var item in items) {
var currentAge = items[item].age;
if(!buckets[currentAge]) {
buckets[currentAge] = [];
for (var i in items) {
if (currentAge === items[i].age) {
buckets[currentAge].push(items[i]);
}
}
}
}
var items = [
{name:"Foo", age:16, color:"w"},
{name:"Bar", age:18, color:"b"},
{name:"foo", age:16, color:"w"},
{name:"bar", age:18, color:"w"},
{name:"foobar", age:18, color:"b"},
{name:"barfoo", age:20, color:"w"}
];
var result = [] // THIS IS THE RESULTING ARRAY THAT YOU WANT
function find(age) {
for (var i = 0; i < result.length; i++)
if (result[i].age == age) return i
return -1
}
function append(i, obj) {
result[i].name.push(obj.name)
result[i].color.push(obj.color)
}
for (var i = 0; i < items.length; i++) {
var x = find(items[i].age)
if (x < 0) result.push({ age: items[i].age, name: [items[i].name], color : [items[i].color]})
else append(x, items[i])
}
console.log(result) // PRINT THE RESULT, alternatively you can use alert(result)
The output
[ { age: 16, name: [ 'Foo', 'foo' ], color: [ 'w', 'w' ] },
{ age: 18, name: [ 'Bar', 'bar', 'foobar' ], color: [ 'b', 'w', 'b' ] },
{ age: 20, name: [ 'barfoo' ], color: [ 'w' ] } ]