This question already has answers here:
Javascript: Merge Array of Objects, summing values with same key
(1 answer)
How to merge two arrays of objects, and sum the values of duplicate object keys in JavaScript?
(2 answers)
Closed 9 months ago.
let obj = [
{
name: "a",
quantity: 2
},
{
name: "b",
quantity: 4
},
{
name: "c",
quantity: 88
}
]
let obj2 = [
{
name: "a",
quantity: 2
}
]
I want to group two object array but if object which has a same name already exists then merge.
For example, there are objects which name is "a" and I want to merge them together.
Output what I want is like
[
{
name: "a",
quantity: 4
},
{
name: "b",
quantity: 4
},
{
name: "c",
quantity: 88
}
]
The quantity of object which name is "a" is add together.
Is there anyway to do this?
let obj = [
{
name: "a",
quantity: 2
},
{
name: "b",
quantity: 4
},
{
name: "c",
quantity: 88
}
]
let obj2 = [
{
name: "a",
quantity: 2
}
]
let obj3 = [...obj, ...obj2];
let obj4 = obj3.reduce( (curr, ele) => {
let exist = curr.filter( cur => cur.name == ele.name)
if (exist.length) exist[0].quantity += ele.quantity
else curr.push({...ele})
return curr
}, [])
let obj5 = Object.values(
obj3.reduce((res, {name, quantity}) => {
let ele = res[name] ??= {name}
ele['quantity'] = (ele['quantity'] ?? 0) + quantity
return res
}, {})
)
console.log(obj4, obj5)
You can use forEach() for this.
let obj = [
{
name: "a",
quantity: 2
},
{
name: "b",
quantity: 4
},
{
name: "c",
quantity: 88
}
]
let obj2 = [
{
name: "a",
quantity: 2
}
]
obj.forEach((element)=>{
obj2.forEach((e)=>{
if(element.name == e.name){
element.quantity = element.quantity+e.quantity
}
})
})
console.log(obj);
Related
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})
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))
})
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);
I want to dynamically add new attribute to all of the items in an array using map. But while adding it to each item, the value of this attribute is the sum of all previous items newly added attribute
Consider this example :
let persons = [{
"name": "A",
"salary": 2
}, {
"name": "B",
"salary": 5
},{
"name":"C",
"salary":12
}];
I want to return :
[{
"name": "A",
"salary": 2,
"sumSalary":2
}, {
"name": "B",
"salary": 5,
"sumSalary":7
},{
"name":"C",
"salary":12,
"sumSalary":19
}];
I've tried this one:
let mutatedPersons = persons.map((currentValue, index, mutatedPersons) => ({
...currentValue,
sumSalary: currentValue.name === 'A' ? currentValue.salary : mutatedPersons[index - 1].sumSalary + currentValue.salary
}))
but i keep getting this :
[
0: {name: "A", salary: 2, sumSalary: 2}
1: {name: "B", salary: 5, sumSalary: NaN}
2: {name: "C", salary: 12, sumSalary: NaN}
]
The mutatedPersons you refer to is the original array (see map's parameters), and not the updated array, which doesn't actually exist before the map end. You can cache the previous sum in an external variable (prevSumSalary), and use it as the basis of the new one:
const persons = [{ name: "A", salary: 2 }, { name: "B", salary: 5 }, { name: "C", salary: 12 }]
let prevSumSalary = 0;
const mutatedPersons = persons.map((currentValue, index) => ({
...currentValue,
sumSalary: (prevSumSalary = prevSumSalary + currentValue.salary)
}))
console.log(mutatedPersons);
Another option is to use Array.reduce(), since you have access to the accumulated values:
const persons = [{ name: "A", salary: 2 }, { name: "B", salary: 5 }, { name: "C", salary: 12 }]
const mutatedPersons = persons.reduce((r, currentValue) => [...r,
({
...currentValue,
sumSalary: currentValue.salary + (r.length && r[r.length - 1].sumSalary)
})
], [])
console.log(mutatedPersons);
You could use a closure over sum and take it for added sumSalary property.
var data = [{ name: "A", salary: 2 }, { name: "B", salary: 5 }, { name: "C", salary: 12 }],
result = data.map((sum => o => ({ ...o, sumSalary: sum += o.salary }))(0));
console.log(result);
let persons = [{
"name": "A",
"salary": 2
}, {
"name": "B",
"salary": 5
},{
"name":"C",
"salary":12
}];
let sum = 0;
persons.map(curr => {
sum += curr.salary;
curr.sumSalary = sum;
});
console.log(persons);
This is an ideal case for Array#reduce.
One can use an accumulator (the whole salarySum) to get direct access to the last salarySum value.
Whenever one thinks about an aggregate function, one should immediately think about Array#reduce in first place!
Also, I've provided you a solution which doesn't mutate the source persons but it creates a new array which has salarySum on each item:
const persons = [{
name: "A",
salary: 2
}, {
name: "B",
salary: 5
}, {
name: "C",
salary: 12
}]
const {
persons: persons_,
salarySum
} = persons.reduce((result, person) =>
result.persons.push({
...person,
salarySum: (result.salarySum += person.salary)
}) && result, {
salarySum: 0,
persons: []
})
console.log(persons_)
console.log(salarySum)
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)