how to merge arrays which contains objects? - javascript

I have more than two arrays with objects which have some similar properties,
and I want to merge all arrays to one array and sort theme as bellow:
array = [
[ { "name" : "Jack", count: 10 }, { "name": "Fred", "count": 20 } ],
[ { "name": "Jack", count: 3 }, { "name": "Sara", "count": 10 } ]
]
merged_array = [
{ "name": "Fred", "count": 20 },
{ "name": "Jack", "count": 13 },
{ "name": "Sara", "count": 10 }
]

array
.reduce(function(result, arrayItem) {
result = result || [];
// sort also can be implemented here
// by using `Insertion sort` algorithm or anyone else
return result.concat(arrayItem);
})
.sort(function(a,b) { return a.count < b.count; })

You can use two forEach() to get array with merged objects and then sort it with sort().
var array = [
[{
"name": "Jack",
count: 10
}, {
"name": "Fred",
"count": 20
}],
[{
"name": "Jack",
count: 3
}, {
"name": "Sara",
"count": 10
}]
]
var result = [];
array.forEach(function(a) {
var that = this;
a.forEach(function(e) {
if (!that[e.name]) {
that[e.name] = e;
result.push(that[e.name]);
} else {
that[e.name].count += e.count
}
})
}, {})
result.sort(function(a, b) {
return b.count - a.count;
})
console.log(result)

If you are open to, then do take a look at to underscorejs, it is a wonderful utility for working with Arrays and objects as such. This will allow you to write flexible and transparent logic. The documentation is also quite good.
var arrays = [
[{
"name": "Jack",
count: 10
}, {
"name": "Fred",
"count": 20
}],
[{
"name": "Jack",
count: 3
}, {
"name": "Sara",
"count": 10
}]
]
var result = _.chain(arrays)
.flatten()
.union()
// whatever is the "key" which binds all your arrays
.groupBy('name')
.map(function(value, key) {
var sumOfCount = _.reduce(value, function(entry, val) {
// the fields which will need to be "aggregated"
return entry + val.count;
}, 0);
return {
'name': key,
'count': sumOfCount
};
}
)
// you can have your own sorting here
.sortBy('count')
.value();
console.log(result.reverse());
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Related

New Map from JSON data with unique values

I'm trying to create a new map of [key:value] as [trait_type]:[{values}]
So taking the below data it should look like:
[Hair -> {"Brown", "White-Blue"},
Eyes -> {"Green", "Red"}
]
Heres my json obj
[
{
"name":"Charlie",
"lastname":"Gareth",
"date":1645462396133,
"attributes":[
{
"trait_type":"Hair",
"value":"Brown"
},
{
"trait_type":"Eyes",
"value":"Red"
}
]
},
{
"name":"Bob",
"lastname":"James",
"date":1645462396131,
"attributes":[
{
"trait_type":"Hair",
"value":"White-Blue"
},
{
"trait_type":"Eyes",
"value":"green"
}
]
}
];
To note: I'm also trying to make it the values unique so If I have 2 people with red eyes the value would only ever appear once.
This is what I have so far, kind of works but in the console window the values come out as a char array.
let newData = data.map((item) =>
item.attributes.map((ats) => {
return { [ats.trait_type]: [...ats.value] };
})
);
newData.map((newItem) => console.log(newItem));
You could take an object and iterate the nested data with a check for seen values.
const
data = [{ name: "Charlie", lastname: "Gareth", date: 1645462396133, attributes: [{ trait_type: "Hair", value: "Brown" }, { trait_type: "Eyes", value: "Red" }] }, { name: "Bob", lastname: "James", date: 1645462396131, attributes: [{ trait_type: "Hair", value: "White-Blue" }, { trait_type: "Eyes", value: "green" }] }],
result = data.reduce((r, { attributes }) => {
attributes.forEach(({ trait_type, value }) => {
r[trait_type] ??= [];
if (!r[trait_type].includes(value)) r[trait_type].push(value);
})
return r;
}, {});
console.log(result);
try this
const extractTrait = data =>
data.flatMap(d => d.attributes)
.reduce((res, {
trait_type,
value
}) => {
return {
...res,
[trait_type]: [...new Set([...(res[trait_type] || []), value])]
}
}, {})
const data = [{
"name": "Charlie",
"lastname": "Gareth",
"date": 1645462396133,
"attributes": [{
"trait_type": "Hair",
"value": "Brown"
},
{
"trait_type": "Eyes",
"value": "Red"
}
]
},
{
"name": "Bob",
"lastname": "James",
"date": 1645462396131,
"attributes": [{
"trait_type": "Hair",
"value": "White-Blue"
},
{
"trait_type": "Eyes",
"value": "green"
}
]
}
];
console.log(extractTrait(data))

String-path to Tree (JavaScript)

I have an array of paths in string format like that:
[
{ _id: 'women/clothes/tops', count: 10 },
{ _id: 'women/clothes/suits', count: 5 },
{ _id: 'women/accessories', count: 2 },
{ _id: 'men/clothes', count: 1 },
]
I would like to group them into a tree structure like that:
[
{
_id: 'women',
count: 17,
children: [
{
_id: 'clothes',
count: 15,
children: [
{ _id: 'tops', count: 10 },
{ _id: 'suits', count: 5 }
]
},
{
_id: 'accessories',
count: 2
}
]
},
{
_id: 'men',
count: 1,
children: [
{
_id: 'clothes',
count: 1
}
]
}
]
I would imagine a sort of recursive function calling a reduce method. But I can't figure how exactly.
EDIT :
I managed to get close with this solution. But I still get an empty object key, and i cannot manage to not have the children key when there are no children:
const getTree = (array) => {
return array.reduce((a, b) => {
const items = b._id.replace('\/', '').split('/')
return construct(a, b.count, items)
}, {})
}
const construct = (a, count, items) => {
const key = items.shift()
if(!a[key]) {
a[key] = {
_id: key,
count: count,
children: []
}
a[key].children = items.length > 0 ? construct(a[key].children, count, items) : null
}
else {
a[key].count += count
a[key].children = items.length > 0 ? construct(a[key].children, count, items) : null
}
return a
}
I created an object tree first and then converted that to your array of objects with children structure.
Note: I used a _count property on each object in the intermediate structure so that when looping over the keys later (when creating the final structure), I could ignore both _id and _count easily, and loop over only the "real children" keys, which don't start with _.
I did not look at your current attempt/solution before writing this, so mine looks quite different.
const origData = [
{ _id: 'women/clothes/tops', count: 10 },
{ _id: 'women/clothes/suits', count: 5 },
{ _id: 'women/accessories', count: 2 },
{ _id: 'men/clothes', count: 1 },
];
const newObj = {};
for (let obj of origData) {
//console.log(obj)
const tempArr = obj._id.split('/');
let tempHead = newObj; // pointer
for (let idx in tempArr) {
let head = tempArr[idx];
if (!tempHead.hasOwnProperty(head)) {
tempHead[head] = {};
}
tempHead = tempHead[head];
tempHead._id = head;
const currCount = tempHead._count || 0;
tempHead._count = currCount + obj.count;
}
tempHead._count = obj.count;
}
console.log(newObj);
const finalArr = [];
let tempArrHead = finalArr; // pointer
let tempObjHead = newObj; // pointer
function recursiveStuff(currObj, currArr, copyObj) {
let hasChildren = false;
const keys = Object.keys(currObj).filter(a => !a.startsWith("_"));
for (let key of keys) {
hasChildren = true;
const obj = {
_id: currObj[key]._id,
count: currObj[key]._count || 0,
children: [],
};
currArr.push(obj);
recursiveStuff(currObj[key], obj.children, obj)
}
if (hasChildren == false) {
// console.log(copyObj);
// there might be a more elegant way, but this works:
delete copyObj.children;
}
}
recursiveStuff(tempObjHead, tempArrHead)
console.log(finalArr);
.as-console-wrapper{
max-height: 100% !important;
}
Intermediate Structure:
{
"women": {
"_id": "women",
"_count": 17,
"clothes": {
"_id": "clothes",
"_count": 15,
"tops": {
"_id": "tops",
"_count": 10
},
"suits": {
"_id": "suits",
"_count": 5
}
},
"accessories": {
"_id": "accessories",
"_count": 2
}
},
"men": {
"_id": "men",
"_count": 1,
"clothes": {
"_id": "clothes",
"_count": 1
}
}
}
Final Structure:
[
{
"_id": "women",
"count": 17,
"children": [
{
"_id": "clothes",
"count": 15,
"children": [
{"_id": "tops", "count": 10},
{"_id": "suits", "count": 5}
]
},
{"_id": "accessories", "count": 2}
]
},
{
"_id": "men",
"count": 1,
"children": [
{"_id": "clothes", "count": 1}
]
}
]

How to group from array object

I using code form "
I am looking for best ways of doing this. I have group:
data
[
{
"date": "16/04/2020",
"count": 0,
"name": "A"
},
{
"date": "16/04/2020",
"count": 1,
"name": "B"
},
{
"date": "17/04/2020",
"count": 0,
"name": "B"
}
//...More.....
]
Answer
{
"date": "04/2020",
"symtom": {
"data": [
{
"date": "16/04/2020",
"data": [
{
"name": "A",
"count": [
{
"date": "16/04/2020",
"count": 0,
"name": "A"
}
]
},
{
"name": "B",
"count": [
{
"date": "16/04/2020",
"count": 1,
"name": "B"
}
]
},
//...More.....
]
},
{
"date": "17/04/2020",
"data": [
{
"name": "B",
"count": [
{
"date": "17/04/2020",
"count": 0,
"name": "B"
}
]
},
//...More.....
]
}
]
}
}
Can I fix the code and to get the desired answer?
Code :
const items = [
{
tab: 'Results',
section: '2017',
title: 'Full year Results',
description: 'Something here',
},
{
tab: 'Results',
section: '2017',
title: 'Half year Results',
description: 'Something here',
},
{
tab: 'Reports',
section: 'Marketing',
title: 'First Report',
description: 'Something here',
}
];
function groupAndMap(items, itemKey, childKey, predic){
return _.map(_.groupBy(items,itemKey), (obj,key) => ({
[itemKey]: key,
[childKey]: (predic && predic(obj)) || obj
}));
}
var result = groupAndMap(items,"tab","sections",
arr => groupAndMap(arr,"section", "items"));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
ref : Group array of object nesting some of the keys with specific names
But I would like to have the answer line this (Answer) :
{
"date": "04/2020",
"symtom": {
"data": [
{
"date": "16/04/2020",
"data": [
{
"name": "A",
"count": 0,
},
{
"name": "B",
"count": 1,
},
//...More.....
]
},
{
"date": "17/04/2020",
"data": [
{
"name": "B",
"count":0,
},
//...More.....
]
}
]
}
}
Thanks!
I am a beginner but it looks like you want system.data.data to = an array of objects with the keys name:str and count:number but instead you are applying the whole object into count so the key count:{name:A, count:0,date:etc}.
I really can't follow your function which separates the data... but all you should have to do is when count is sent the object to reference just do a dot notation like object.count to access the number vs the object that way you will have the desired affect. Hopefully that is what you were asking.
I would use a helper function groupBy (this version is modeled after the API from Ramda [disclaimer: I'm one of its authors], but it's short enough to just include here.) This takes a function that maps an object by to a key value, and then groups your elements into an object with those keys pointing to arrays of your original element.
We need to use that twice, once to group by month and then inside the results to group by day. The rest of the transform function is just to format your output the way I think you want.
const groupBy = (fn) => (xs) =>
xs .reduce((a, x) => ({... a, [fn(x)]: [... (a [fn (x)] || []), x]}), {})
const transform = (data) =>
Object .entries (groupBy (({date}) => date.slice(3)) (data)) // group by month
.map (([date, data]) => ({
date,
symtom: {
data: Object .entries (groupBy (({date}) => date) (data)) // group by day
.map (([date, data]) => ({
date,
data: data .map (({date, ...rest}) => ({...rest})) // remove date property
}))
}
}))
const data = [{date: "16/04/2020", count: 0, name: "A"}, {date: "16/04/2020", count: 1, name: "B"}, {date: "17/04/2020", count: 0, name: "B"}, {date: "03/05/2020", count: 0, name: "C"}];
console .log (
transform (data)
)
.as-console-wrapper {min-height: 100% !important; top: 0}
If you need to run in an environment without Object.entries, it's easy enough to shim.
You could take a function for each nested group and reduce the array and the grouping levels.
var data = [{ date: "16/04/2020", count: 0, name: "A" }, { date: "16/04/2020", count: 1, name: "B" }, { date: "17/04/2020", count: 0, name: "B" }],
groups = [
(o, p) => {
var date = o.date.slice(3),
temp = p.find(q => q.date === date);
if (!temp) p.push(temp = { date, symptom: { data: [] } });
return temp.symptom.data;
},
({ date }, p) => {
var temp = p.find(q => q.date === date);
if (!temp) p.push(temp = { date, data: [] });
return temp.data;
},
({ date, ...o }, p) => p.push(o)
],
result = data.reduce((r, o) => {
groups.reduce((p, fn) => fn(o, p), r);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comparing the keys of two JavaScript objects

I've got two sets of JavaScript objects. I want to compare object1 to object2, and then get a list of all the keys that are in object1, but not in object2. I've searching for resources to help me, but I've only ended up finding comparison functions for simple objects. The objects that I want to compare have a lot of nesting. I've included an example at the bottom.
How would I go about making a function for comparing these two objects? Is it possible to create a flexible function, that would also work if the objects were to change and contain more nesting?
const object1 = {
"gender": "man",
"age": 33,
"origin": "USA",
"jobinfo": {
"type": "teacher",
"school": "Wisconsin"
},
"children": [
{
"name": "Daniel",
"age": 12,
"pets": [
{
"type": "cat",
"name": "Willy",
"age": 2
},
{
"type": "dog",
"name": "jimmie",
"age": 5
}
]
},
{
"name": "Martin",
"age": 14,
"pets": [
{
"type": "bird",
"name": "wagner",
"age": 12
}
]
}
],
"hobbies": {
"type": "football",
"sponsor": {
"name": "Pepsi",
"sponsorAmount": 1000,
"contact": {
"name": "Leon",
"age": 59,
"children": [
{
"name": "James",
"pets": [
{
"type": "dog",
"age": 4
}
]
}
]
}
}
}
}
const object2 = {
"gender": "man",
"jobinfo": {
"type": "teacher"
},
"children": [
{
"name": "Daniel",
"age": 12,
"pets": [
{
"type": "cat",
"name": "Willy",
"age": 2
},
{
"type": "dog",
"name": "jimmie",
"age": 5
}
]
}
]
}
So what I want to achieve by comparing these two objects, is in this case to have an array return that consists of the keys that are in object1, but not object2. So the array would look something like this.
["age", "hobbies", "type", "sponsor", "name", "sponsorAmount", "contact", "name", "age", "children", "name", "pets", "type", "age"].
This is what I've gotten to so far. This is sort of working. But it's not printing out age for example, because age is a property that exists in multiple of the nested objects.
jsfiddle: https://jsfiddle.net/rqdgojq2/
I've had a look at the following resources:
https://stackoverflow.com/a/25175871/4623493
https://stackoverflow.com/a/21584651/4623493
Complex solution using Set object and custom getAllKeyNames() recursive function to get all unique key names from specified object:
var object1 = {"gender":"man","age":33,"origin":"USA","jobinfo":{"type":"teacher","school":"Wisconsin"},"children":[{"name":"Daniel","age":12,"pets":[{"type":"cat","name":"Willy","age":2},{"type":"dog","name":"jimmie","age":5}]},{"name":"Martin","age":14,"pets":[{"type":"bird","name":"wagner","age":12}]}],"hobbies":{"type":"football","sponsor":{"name":"Pepsi","sponsorAmount":1000,"contact":{"name":"Leon","age":59,"children":[{"name":"James","pets":[{"type":"dog","age":4}]}]}}}},
object2 = {"gender":"man","age":33,"origin":"USA","jobinfo":{"type":"teacher","school":"Wisconsin"},"children":[{"name":"Daniel","age":12,"pets":[{"type":"cat","name":"Willy","age":2},{"type":"dog","name":"jimmie","age":5}]}]};
function getAllKeyNames(o, res){
Object.keys(o).forEach(function(k){
if (Object.prototype.toString.call(o[k]) === "[object Object]") {
getAllKeyNames(o[k], res);
} else if (Array.isArray(o[k])) {
o[k].forEach(function(v){
getAllKeyNames(v, res);
});
}
res.add(k);
});
}
var o1Keys = new Set(), o2Keys = new Set();
getAllKeyNames(object1, o1Keys); // unique keys of object1
getAllKeyNames(object2, o2Keys); // unique keys of object2
// get a list of all the keys that are in object1, but not in object2
var diff = [...o1Keys].filter((x) => !o2Keys.has(x));
console.log(diff);
Thanks for the feedback.
I ended up solving it, with a lot of inspiration from Romans answer.
const compareObjects = (obj1, obj2) => {
function getAllKeyNames(o, arr, str){
Object.keys(o).forEach(function(k){
if (Object.prototype.toString.call(o[k]) === "[object Object]") {
getAllKeyNames(o[k], arr, (str + '.' + k));
} else if (Array.isArray(o[k])) {
o[k].forEach(function(v){
getAllKeyNames(v, arr, (str + '.' + k));
});
}
arr.push(str + '.' + k);
});
}
function diff(arr1, arr2) {
for(let i = 0; i < arr2.length; i++) {
arr1.splice(arr1.indexOf(arr2[i]), 1);
}
return arr1;
}
const o1Keys = [];
const o2Keys = [];
getAllKeyNames(obj1, o1Keys, ''); // get the keys from schema
getAllKeyNames(obj2, o2Keys, ''); // get the keys from uploaded file
const missingProps = diff(o1Keys, o2Keys); // calculate differences
for(let i = 0; i < missingProps.length; i++) {
missingProps[i] = missingProps[i].replace('.', '');
}
return missingProps;
}
jsfiddle here: https://jsfiddle.net/p9Lm8b53/
You could use an object for counting.
function getCount(object, keys, inc) {
Object.keys(object).forEach(function (k) {
if (!Array.isArray(object)) {
keys[k] = (keys[k] || 0) + inc;
if (!keys[k]) {
delete keys[k];
}
}
if (object[k] && typeof object[k] === 'object') {
getCount(object[k], keys, inc)
}
});
}
var object1 = { gender: "man", age: 33, origin: "USA", jobinfo: { type: "teacher", school: "Wisconsin" }, children: [{ name: "Daniel", age: 12, pets: [{ type: "cat", name: "Willy", age: 2 }, { type: "dog", name: "jimmie", age: 5 }] }, { name: "Martin", age: 14, pets: [{ type: "bird", name: "wagner", age: 12 }] }], hobbies: { type: "football", sponsor: { name: "Pepsi", sponsorAmount: 1000, contact: { name: "Leon", age: 59, children: [{ name: "James", pets: [{ type: "dog", age: 4 }] }] } } } },
object2 = { gender: "man", jobinfo: { type: "teacher" }, children: [{ name: "Daniel", age: 12, pets: [{ type: "cat", name: "Willy", age: 2 }, { type: "dog", name: "jimmie", age: 5 }] }] },
count = {};
getCount(object1, count, 1);
getCount(object2, count, -1);
console.log(count);
.as-console-wrapper { max-height: 100% !important; top: 0; }
This recursive approach works best for me.
let object1 = {
a: 40,
b: 80,
c: 120,
xa: [
{
xc: 12,
xz: 12
}
],
rand: 12
};
let object2 = {
a: 20,
b: 30,
c: 40,
xa: [
{
xy: 12,
xz3: 12
}
]
};
function getObjDifferences(obj, obj2, propsMissing, keyName) {
Object.keys(obj).forEach(key => {
if(obj2[key] === undefined) {
if(keyName.length > 0) propsMissing.push(keyName+"->"+key);
else propsMissing.push(key)
} else if (typeof obj[key] === 'object' && obj[key] !== null) {
if(obj2[key] !== undefined) {
if(keyName.length > 0) getObjDifferences(obj[key], obj2[key], propsMissing, keyName+"->"+key)
else getObjDifferences(obj[key], obj2[key], propsMissing, key)
} else {
propsMissing.push(key)
}
}
})
return propsMissing;
}
console.log(getObjDifferences(object1, object2, [], ''))
console.log(getObjDifferences(object2, object1, [], ''))

Slice properties from objects and counting

Is it possible to slice single property from array of objects like
[{"name":"Bryan","id":016, "counter":0}, {"name":"John","id":04, "counter":2}, {"name":"Alicia","id":07, "counter":6}, {"name":"Jenny","id":015, "counter":9}, {"name":"Bryan","id":016, "counter":0}, {"name":"Jenny","id":015, "counter":9}, {"name":"John","id":04, "counter":2}, {"name":"Jenny" ,"id":015, "counter":9}];
I'm trying to slice name from every object and count number of the same elements (there are 3 objects with name Jenny) in order to achieve the following structure:
[{"name":"Bryan","Number":2},
{"name":"John","Number":2},
{"name":"Alicia","Number":1},
{"name":"Jenny","Number":3}]
Do you want to ignore the id and counter props already present?
You could create an object to keep track of the unique names, and convert back to an array in the end:
var data = [{"name": "Bryan", "id": 016, "counter": 0}, { "name": "John", "id": 04, "counter": 2}, { "name": "Alicia", "id": 07, "counter": 6}, { "name": "Jenny", "id": 015, "counter": 9}, { "name": "Bryan", "id": 016, "counter ": 0}, { "name": "Jenny", "id": 015, "counter ": 9}, { "name": "John", "id": 04, "counter": 2}, { "name": "Jenny", "id": 015, "counter": 9}];
var result = data.reduce(function(result, item) {
if (!result[item.name]) {
result[item.name] = {
name: item.name,
counter: 0
};
}
result[item.name].counter += 1;
return result;
}, {});
console.log(Object.keys(result).map(function(key) { return result[key] }));
You could use a hash table as a reference to the counted names.
var data = [{ name: "Bryan", id: "016", counter: 0 }, { name: "John", id: "04", counter: 2 }, { name: "Alicia", id: "07", counter: 6 }, { name: "Jenny", id: "015", counter: 9 }, { name: "Bryan", id: "016", counter: 0 }, { name: "Jenny", id: "015", counter: 9 }, { name: "John", id: "04", counter: 2 }, { name: "Jenny", id: "015", counter: 9 }],
grouped = [];
data.forEach(function (a) {
if (!this[a.name]) {
this[a.name] = { name: a.name, Number: 0 };
grouped.push(this[a.name]);
}
this[a.name].Number++;
}, Object.create(null));
console.log(grouped);
Give this a shot. We create a dictionary of names with their counts called nameDict, and iterate through the list to count them.
var arr = [{"name":"Bryan","id":"016", "counter":0}, {"name":"John","id":"04", "counter":2}, {"name":"Alicia","id":"07", "counter":6}, {"name":"Jenny","id":"015", "counter":9}, {"name":"Bryan","id":"016", "counter":0}, {"name":"Jenny","id":"015", "counter":9}, {"name":"John","id":"04", "counter":2}, {"name":"Jenny","id":"015", "counter":9}];
var nameDict = {};
for(var i = 0; i < arr.length; i++)
{
var name = arr[i].name;
if(nameDict[name] == undefined){
//haven't encountered this name before so we need to create a new entry in the dict
nameDict[name] = 1
} else {
//otherwise increment the count
nameDict[name] += 1
}
}
console.log(JSON.stringify(nameDict));

Categories

Resources