This question already has answers here:
Group array items using object
(19 answers)
How can I group an array of objects by key?
(32 answers)
Closed 7 months ago.
I want to make this
const arr = [
{
"name": "mac"
},
{
"group": "others",
"name": "lenovo"
},
{
"group": "others",
"name": "samsung"
}
]
into this:
[
{
name: 'mac',
},
{
name: 'others',
group: [
{
name: 'lenovo',
},
{
name: 'samsung',
},
],
}
]
I tried to use normal forEach loop but it didn't turn out well:
let final = []
const result = arr.forEach(o => {
if(o.group) {
group = []
group.push({
name: o.name
})
final.push(group)
} else {
final.push(o)
}
});
Not sure if reduce might help? before I try lodash groupBy I want to use just pure js to try to make it.
Hope this answer will work for you.
const arr = [
{
name: "mac",
},
{
group: "others",
name: "lenovo",
},
{
group: "others",
name: "samsung",
},
];
const temp = [];
arr.forEach((e) => {
if (!e.group) {
temp.push(e);
} else {
const index = temp.findIndex((ele) => ele.name === e.group);
if (index === -1) {
obj = {
name: e.group,
group: [{ name: e.name }],
};
temp.push(obj)
} else {
temp[index].group.push({ name: e.name });
}
}
});
console.log(temp);
instead of creating and pushing group array in final again and again u should just push group in the end of foreach
like this--
let final = []
let group = []
const result = arr.forEach(o => {
if(o.group) {
group.push({
name: o.name
})
} else {
final.push(o)
}
})
final.push({name: "others", group})
Related
I want to filter an array with another array in order to know if there are new people.
const people = [
{ "name": "jerry" },
{ "name": "tom" },
{ "name": "alex" }
]
const newList = [
{ "name": "bran" },
{ "name": "jerry" },
{ "name": "john" }
]
const new_people = []
for (const pp of people) {
let result = newList.filter(newL => newL.name != pp.name)
if (result) {
new_people.push(result)
}
}
console.log(new_people)
This is the result:
[
[ { name: 'bran' }, { name: 'john' } ],
[ { name: 'bran' }, { name: 'jerry' }, { name: 'john' } ],
[ { name: 'bran' }, { name: 'jerry' }, { name: 'john' } ]
]
But I'm looking for:
[ { name: 'bran' }, { name: 'john' } ]
I would like to avoid the loop because it makes duplicate in the result but I don't know how I can't do it without the loop.
First make a temporary array of people name:
const peopleNames = people.map(pp => pp.name);
Then the peopleNames will be as follows:
['jerry', 'tom', 'alex']
Now filter the new people from the newList:
const newPeople = newList.filter(pp => !peopleNames.includes(pp.name));
The newPeople will be an array of objects that you are looking for.
[{name: 'bran'}, {name: 'john'}]
const people = [
{ "name": "jerry" },
{ "name": "tom" },
{ "name": "alex" }
]
const newList = [
{ "name": "bran" },
{ "name": "jerry" },
{ "name": "john" }
]
const output = newList.filter(a => people.filter(x => x.name == a.name).length == 0);
console.log('By USing Filter', output);
//filter the newList and retain those object, which are not present in the people
//Way 2: By using some
//const output2 = newList.filter(a => !people.some(x => x.name == a.name));
//console.log('By Using Some', output2);
You can use Array's reduce method to get the desired result:
const new_people = newList.reduce((accVal, e) =>
(people.map(p => p.name).includes(e.name))
? accVal
: accVal.concat({ "name": e.name } ),
[ ] )
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);
This question already has answers here:
Filter array of objects with another array of objects
(11 answers)
Closed 1 year ago.
const items = [[{name:"p2"},{name:"p3"}, {name:"p7"},{name:"p9"},{name:"p1"}],[{name:"p6"}, {name:"p3"},{name:"p7"}, {name:"p9"},{name:"p2"}],[{name:"p3"},{name:"p6"}, {name:"p7"},{name:"p9"},{name:"p4"}],[{name:"p2"}, {name:"p3"},{name:"p1"}, {name:"p9"},{name:"p6"}]]
const findObj = [{name:"p1"},{name:"p2"},{name:"p6"}]
Find the child array of sets which have all three element from findobj object
You can easily achieve the result using filter, Set and reduceas:
const items = [
[
{ name: "p2" },
{ name: "p3" },
{ name: "p7" },
{ name: "p9" },
{ name: "p1" },
],
[
{ name: "p6" },
{ name: "p3" },
{ name: "p7" },
{ name: "p9" },
{ name: "p2" },
],
[
{ name: "p3" },
{ name: "p6" },
{ name: "p7" },
{ name: "p9" },
{ name: "p4" },
],
[
{ name: "p2" },
{ name: "p3" },
{ name: "p1" },
{ name: "p9" },
{ name: "p6" },
],
];
const findObj = [{ name: "p1" }, { name: "p2" }, { name: "p6" }];
const set = new Set(findObj.map((o) => o.name));
const result = items.filter((arr) => {
const remain = arr.reduce((acc, curr) => {
if (set.has(curr.name)) acc.add(curr.name);
return acc;
}, new Set());
return remain.size === set.size;
});
console.log(result);
const items = [[{name:"p2"},{name:"p3"}, {name:"p7"},{name:"p9"},{name:"p1"}],[{name:"p6"}, {name:"p3"},{name:"p7"}, {name:"p9"},{name:"p2"}],[{name:"p3"},{name:"p6"}, {name:"p7"},{name:"p9"},{name:"p4"}],[{name:"p2"}, {name:"p3"},{name:"p1"}, {name:"p9"},{name:"p6"}]]
const findObj = [{name:"p1"},{name:"p2"},{name:"p6"}]
const result = items.filter(item=>{
const childItem = item.map(childItem=>childItem.name);
let allExist=true;
findObj.forEach(obj=>{
if(!childItem.includes(obj.name)){
allExist=false;
}
})
return allExist;
})
console.log(result)
Using filter and get all names from each item by using map .map(prop=>prop.name) or more simple with destructuring .map(({name})=>name) and filter items that names are included in findObj
const items = [[{name:"p2"},{name:"p3"}, {name:"p7"},{name:"p9"},{name:"p1"}],[{name:"p6"}, {name:"p3"},{name:"p7"}, {name:"p9"},{name:"p2"}],[{name:"p3"},{name:"p6"}, {name:"p7"},{name:"p9"},{name:"p4"}],[{name:"p2"}, {name:"p3"},{name:"p1"}, {name:"p9"},{name:"p6"}]]
const findObj = [{name:"p1"},{name:"p2"},{name:"p6"}]
const result = items.filter(item=>{
const arrProp = item.map(prop=>prop.name)
const filtProp = findObj.map(({name})=>name)
return filtProp.every(x=>arrProp.includes(x));
})
console.log(result)
This question already has answers here:
Merge two array of objects based on a key
(23 answers)
Closed 1 year ago.
I have two arrays as input (array1 & array2) for which I want to check if there is a match on id.
If there is a match they should be included in a new array called result.
array1 = [
{ x_id:6711230070958, id:279482 },
{ x_id:6770878283950, id:213 },
{ x_id:6753301168302, id:330120 }
];
array2 = [
{ id: 279482, stock: 9 },
{ id: 31231, stock: 2 },
{ id: 330120, stock: 2 }
];
result [
{ x_id:6711230070958, id: 279482, stock: 9 },
{ x_id:6753301168302, id: 330120, stock: 2 }
]
For finding the matches I tried using a filter with includes.
Anybody some thoughts on this?
Try this
array1 = [
{ x_id:6711230070958, id:279482 },
{ x_id:6770878283950, id:213 },
{ x_id:6753301168302, id:330120 }
];
array2 = [
{ id: 279482, stock: 9 },
{ id: 31231, stock: 2 },
{ id: 330120, stock: 2 }
];
let arr3 = array1.map((item, i) => Object.assign({}, item, array2[i]));
console.log(arr3)
Try this:
array1 = [
{ x_id:6711230070958, id:279482 },
{ x_id:6770878283950, id:213 },
{ x_id:6753301168302, id:330120 }
];
array2 = [
{ id: 279482, stock: 9 },
{ id: 31231, stock: 2 },
{ id: 330120, stock: 2 }
];
result = [];
array1.forEach(ele=> {
let match = array2.find(e => e.id == ele.id);
if(match)
result.push(Object.assign({}, ele, match))
})
This question already has answers here:
Remove duplicates form an array
(17 answers)
Closed 5 years ago.
I have this array?
var arr = [{id:"1",Name:"Tom"},
{id:"2",Name:"Jon"},
{id:"3",Name:"Tom"},
{id:"4",Name:"Jack"}]
From array above I need to fecth all existing Names distinct.
var result = getNamesDistinct(arr);
The result should contain result is:
["Tom","Jon","Jack"];
My question is how to get all existing Names from arr distinct?
If Set is available, you can simply do
new Set(arr.map(obj => obj.Name))
(pass the set to Array.from if you need an array)
You can do it via Set object
const arr = [
{ id: "1", Name: "Tom" },
{ id: "2", Name: "Jon" },
{ id: "3", Name: "Tom" },
{ id: "4", Name: "Jack" }
];
const uniqueNames = [...new Set(arr.map(item => item.Name))];
console.log(uniqueNames);
Or you can iterate over the array and add condition to get only unique names.
const arr = [
{ id: "1", Name: "Tom" },
{ id: "2", Name: "Jon" },
{ id: "3", Name: "Tom" },
{ id: "4", Name: "Jack" }
];
const uniqueNames = arr.reduce(function(arr, item) {
if(arr.indexOf(item.Name) === -1) {
arr.push(item.Name);
}
return arr;
}, []);
console.log(uniqueNames);
you can try this
var array = [{
id: "1",
Name: "Tom"
}, {
id: "2",
Name: "Jon"
}, {
id: "3",
Name: "Tom"
}, {
id: "4",
Name: "Jack"
}]
function uniqueNames(array) {
var newArray = [];
array.forEach((value, key) => {
newArray.push(value.Name)
});
return newArray
}
var myNewArray = uniqueNames(array)