Javascript : Merge objects in array with the same key not working - javascript

I am trying to get the same group names to merge together. I have looked around to get an idea of how to do this so I have done some research and I wrote the below code.
This is my implementation that isn't working:
const input = [
{ people: [{ names: "John" }, { names: "Sam" }], group: "one", },
{ people: [{ names: "George" }], group: "one", },
{ people: [{ names: "Bella" }], group: "two",},
];
var output = [];
input.forEach(function(item) {
var existing = output.filter(function(v, i) {
return v.group == item.group;
});
if (existing.length) {
var existingIndex = output.indexOf(existing[0]);
output[existingIndex].people = output[existingIndex].people.concat(item.people);
}
});
console.log(output)
Desired Output:
const output = [
{
people: [{ names: "John" }, { names: "Sam" }, { names: "George" }],
group: "one",
},
{
people: [{ names: "Bella" }],
group: "two",
},
];

Using Array.reduce, you can group by the current array using group key.
And from that grouped object, you can get the result you want.
const input = [
{
people: [{ names: "John" }, { names: "Sam" }],
group: "one",
},
{
people: [{ names: "George" }],
group: "one",
},
{
people: [{ names: "Bella" }],
group: "two",
},
];
const groupByKey = input.reduce((acc, cur) => {
acc[cur.group] ? acc[cur.group].people.push(...cur.people) : acc[cur.group] = cur;
return acc;
}, {});
const output = Object.values(groupByKey);
console.log(output);

Related

Move objects in array where duplicates occur

I have an array of objects, each array has a key of name and then another array of objects:
const myArray = [ { name: "1", item: [{}] }, { name: "2", item: [{}] }, { name: "1", item: [{}] } ]
Now for example sometimes that name key will be the same, i want to be able to check if that name exists and if it does exist push the item into that array object and not into a new object.
The behaviour im getting is above but i would like:
const myArray = [ { name: "1", item: [{ item1, item2 etc }] }, { name: "2", item: [{}] }, { name: "3", item: [{}] } ]
Thanks so much in advance!
You can get the desired result using Array.reduce(), grouping by name.
If two objects in myArray share the same name, the item values are combined.
const myArray = [ { name: "1", item: [{ id: 1 }] }, { name: "2", item: [{ id: 2}] }, { name: "1", item: [{ id: 3}] } ]
const result = Object.values(myArray.reduce((acc, { name, item }) => {
acc[name] = acc[name] || { name, item: [] };
acc[name].item.push(...item);
return acc;
}, {}))
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }
Here's a solution using Array.prototype.reduce function.
const myArray = [ { name: "1", item: [{}] }, { name: "2", item: [{}] }, { name: "1", item: [{}] } ];
const output = myArray.reduce((acc, curr) => {
const index = acc.findIndex(pre => pre.name === curr.name);
if(index !== -1) {
acc[index].item = acc[index].item.concat(curr.item);
} else {
acc.push(curr);
}
return acc;
}, []);
console.log(output);

How filter array of objects based on objects exists in another array of objects?

I have
array1 = [{ name: sample1 }, { name: sample2 }, { name: sample3 }];
array2 = [{ name: sample1 }, { name: sample2 }];
I want to filter objects of array1 which exists in array2.
So I need to have
[{ name: sample1 }, { name: sample2 }]
How can I get it in javascript?
You can use .filter and .some function in JavaScript ,
Here is the example
const array1 = [{ name: "sample1" }, { name: "sample2" }, {
name: "sample3" }];
const array2 = [{ name: "sample1" }, { name: "sample2" }];
let Result = array1.filter(function(obj) {
return array2.some(function(obj2) {
return obj.name== obj2.name;
});
});
console.log(Result)
You can use object destructuring, the map() and .includes() methods as shown below:
const array1 = [{ name: "sample1" }, { name: "sample2" }, { name: "sample3" }];
const array2 = [{ name: "sample1" }, { name: "sample2" }];
const filtered = array1.filter(
({name}) => array2.map(o => o.name).includes(name)
);
console.log( filtered );

Count and update duplicate entries from array

I have an array with duplicated entries.
I'm looking for:
removing all duplicate occurrences
And increment the val propertie off an element if we find an occurrence
here is an exemple of what I have:
const arr = [
{"id":"46","name":"Productivity","val":1},
{"id":"1","name":"test","val":1},
{"id":"43","name":"Health and Fitness","val":1},
{"id":"46","name":"Productivity","val":1},
{"id":"1","name":"test","val":1},
{"id":"46","name":"Productivity","val":1}
]
// Wanted result
const result = [
{"id":"46","name":"Productivity","val":3},
{"id":"43","name":"Health and Fitness","val":1},
{"id":"1","name":"test","val":2}
]
Here is a JsFiddle
You can easily achieve this using reduce and object destructuring.
const arr = [
{ id: "46", name: "Productivity", val: 1 },
{ id: "1", name: "test", val: 1 },
{ id: "43", name: "Health and Fitness", val: 1 },
{ id: "46", name: "Productivity", val: 1 },
{ id: "1", name: "test", val: 1 },
{ id: "46", name: "Productivity", val: 1 },
];
const result = arr.reduce((acc, curr) => {
const { id, name, val } = curr;
const isPresent = acc.find((el) => el.id === id);
if (!isPresent) acc = [...acc, { id, name, val }];
else isPresent.val = isPresent.val + val;
return acc;
}, []);
console.log(result);

Search for an object in a recursive object structure (representing a file system)

I'd like to pass as an input the name of a folder that I want to search for, and get as an output the object that it belongs to.
My array is like this:
const array = {
item: [{
name: "parentFolder1",
item: [{
name: "subFolder1",
item: []
},
{
name: "subFolder2",
item: []
}
]
},
{
name: "parentFolder2",
item: [{
name: "sub1",
item: []
},
{
name: "sub2",
item: []
}
]
}
]
};
const sub = Object.values(array).map(x =>
x.find(y => y.item.find(obj => obj.name = "sub2")))
console.dir(sub)
The output I want:
{
name: "sub2",
item: []
}
The output I get:
[ { name: 'parentFolder1', item: [ [Object], [Object] ] } ]
const array = {
item: [{
name: "parentFolder1",
item: [{
name: "subFolder1",
item: []
},
{
name: "subFolder2",
item: []
}
]
},
{
name: "parentFolder2",
item: [{
name: "sub1",
item: []
},
{
name: "sub2",
item: []
}
]
}
]
};
const val = array.item.map(folder => folder.item.find(obj => obj.name === "sub2")).find(val => val)
console.log(val)
If you need it to be recursive
function find(name, obj) {
if(obj.name === name) return obj;
return obj.item.reduce((result, item) => result || find(name, item), false)
}
const array = {
item: [{
name: "parentFolder1",
item: [{
name: "subFolder1",
item: []
},
{
name: "subFolder2",
item: [{
name: "subsub",
item: [{
name: "searchme",
item: []
}]
}]
}
]
},
{
name: "parentFolder2",
item: [{
name: "sub1",
item: []
},
{
name: "sub2",
item: []
}
]
}
]
};
console.log(find("searchme", array))

join object with the same name into one item

I want to join the objects with the same name into one item array and i don't know how to do it.
I have an array like this :
[
{ name: 'core/core.js',
item: [ [Object] ] },
{ name: 'users/admin.js',
item: [ [Object] ] },
{ name: 'users/admin.js',
item: [ [Object] ] }
]
and i want to have something similar to this :
[
{ name: 'core/core.js',
item: [ [Object] ] },
{ name: 'users/admin.js',
item: [
[ [Object] ],
[ [Object] ]
]
},
]
Here is my code:
const pathFile = [
{ name: 'core/core.js', item: [{ name: 'core' }] },
{ name: 'users/admin.js', item: [{ name: 'admin1' }] },
{ name: 'users/admin.js', item: [{ name: 'admin2' }] },
];
const obj = pathFile.reduce((a, name) => {
if (!a[name]) {
a[name] = { name, files: [] };
}
a[name].files.push({ name });
return a;
}, {});
const arr = Object.values(obj);
console.log(JSON.stringify(arr));
Your problem is that you are using the wrong value for keys inside your reduce() loop. In your code name refers to the whole object inside the reduce so you would need to use name.name for the key because each item, which you are calling name inside the reduce loop has a name property. It might be better to use a different parameter name such as curr so it's clearer.
const pathFile = [{ name: 'core/core.js', item: [{ name: 'core' }] },{ name: 'users/admin.js', item: [{ name: 'admin1' }] },{ name: 'users/admin.js', item: [{ name: 'admin2' }] },];
const obj = pathFile.reduce((a, curr) => {
if (!a[curr.name]) a[curr.name] = curr
else a[curr.name].item.push(...curr.item);
return a;
}, {});
const arr = Object.values(obj);
console.log(arr)

Categories

Resources