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 last month.
I am trying to create a new array of objects by comparing two arrays.One array contains the ids to be compared and the other contains the dataset which should be compared with the first array are a new array of object must be created.
Let me explain this in detail
Consider array 1:
['1','2']
Array 2
[{name:'Linus',id:'1'},{name:'Anthony',id:'1'},{name:'Jake',id:'2'},{name:'Eva',id:'2'}]
What I am expecting as a output is:
[
{id:'1',users:[{name:'Linus',id:'1'},{name:'Anthony',id:'1'}]},
{id:'2',users:[{name:'Jake',id:'2'},{name:'Eva',id:'2'}
]
I am not sure what has to be done.
Something like this for example
const ids = ['1','2'];
const users = [{name:Linus,id:'1'},{name:Anthony,id:'1'},{name:Jake,id:'2'},{name:Eva,id:'2'}];
const groups = ids.map(id =>{
return {
id,
users: users.filter(u => u.id === id)
}
})
const groupBy = ['1','2'];
const data = [{name:'Linus',id:'1'},{name:'Anthony',id:'1'},{name:'Jake',id:'2'},{name:'Eva',id:'2'}];
const result = groupBy.map(id => {
return {
id,
users: data.filter(item => item.id == id),
}
})
console.log(result);
Try this code
Related
This question already has answers here:
How to group by and sum an array of objects? [duplicate]
(2 answers)
Sum JavaScript object propertyA values with the same object propertyB in an array of objects
(12 answers)
Group by, and sum, and generate an object for each array in JavaScript
(4 answers)
ES6 Implementation of Group By and SUM
(4 answers)
Javascript array of objects group and sum items
(4 answers)
Closed last year.
Sorry if this has been asked before, but I couldn't find a good example of what I'm trying to accomplish. Maybe I'm just not searching for the right thing. Please correct me if there's an explanation of this somewhere.
so let's says I have a data like this :
data = [
{"no":1,"location":"New York","transaction":3000},
{"no":2,"location":"Tokyo","transaction":3000},
{"no":3,"location":"New York","transaction":3000},
{"no":4,"location":"Amsterdam","transaction":3000},
{"no":5,"location":"Manchester","transaction":3000},
{"no":6,"location":"New York","transaction":3000},
{"no":7,"location":"Tokyo","transaction":3000},
{"no":8,"location":"Tokyo","transaction":3000},
{"no":9,"location":"New York","transaction":3000},
{"no":10,"location":"Amsterdam","transaction":3000}
]
what i wanted to is an output like this :
result = [
{"location":"New York","transaction":12000},
{"location":"Tokyo","transaction":9000},
{"location":"Amsterdam","transaction":6000}
{"location":"Manchester","transaction":3000}
]
so what i wanted to do is grouping the data based on location and sum the transaction where the location is same and push the data to another array. i don't know where to start, need some help to solve this or any suggestion to solve this using Javascript. thank you
Working Demo :
// Input array
const data = [
{"no":1,"location":"New York","transaction":3000},
{"no":2,"location":"Tokyo","transaction":3000},
{"no":3,"location":"New York","transaction":3000},
{"no":4,"location":"Amsterdam","transaction":3000},
{"no":5,"location":"Manchester","transaction":3000},
{"no":6,"location":"New York","transaction":3000},
{"no":7,"location":"Tokyo","transaction":3000},
{"no":8,"location":"Tokyo","transaction":3000},
{"no":9,"location":"New York","transaction":3000},
{"no":10,"location":"Amsterdam","transaction":3000}
];
// result array
const resultArr = [];
// grouping by location and resulting with an object using Array.reduce() method
const groupByLocation = data.reduce((group, item) => {
const { location } = item;
group[location] = group[location] ?? [];
group[location].push(item.transaction);
return group;
}, {});
// Finally calculating the sum based on the location array we have.
Object.keys(groupByLocation).forEach((item) => {
groupByLocation[item] = groupByLocation[item].reduce((a, b) => a + b);
resultArr.push({
'location': item,
'transaction': groupByLocation[item]
})
})
console.log(resultArr)
This question already has answers here:
Make array objects all have the same keys
(5 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I have a dynamic array which for downstream purposes needs to have all properties define for all objects.
If I have this array:
[
{"Header":"1","Apples":10},
{"Header":"2","Apples":10, "Oranges":153},
{"Header":"3","Oranges":280, "Pears":200},
{"Header":"4","Oranges":1165}
]
How do I fill it out to infill zero values for properties where they exist elsewhere in the array, but not in that object.
Essentially I need to up with this:
[
{"Header":"1","Apples":10, "Oranges":0, "Pears":0},
{"Header":"2","Apples":10, "Oranges":153, "Pears":0},
{"Header":"3","Apples":0, "Oranges":280, "Pears":200},
{"Header":"4","Apples":0, "Oranges":1165,"Pears":0}
]
Header property is essentially the id of each object
const arr = [
{"Header":"1","Apples":10},
{"Header":"2","Apples":10, "Oranges":153},
{"Header":"3","Oranges":280, "Pears":200},
{"Header":"4","Oranges":1165}
];
// get unique keys
let objWithAllProp = arr.reduce((acc, item) => ({...acc, ...item}));
// Get keys as an array and Create an object with all keys set to the default value to 0
let uniqueObjectWithAllProp = Object.keys(objWithAllProp).reduce((acc, key) => {
acc[key] = 0
return acc;
}, {});
// Replace all default values with original, so if key not present in original item, it will be available from uniqueObjectWithAllProp and value default to 0
let result = arr.map((item) => ({...uniqueObjectWithAllProp , ...item}));
console.log(result);
You can get all the existing property values by pushing each item's properties to an array (with Object.keys), then using Set and spread syntax to get the unique.
Then, map over each item in arr and in the loop, loop through the existing property values and check whether the current item has that property. If not, set the value of that property to 0.
const arr = [
{"Header":"1","Apples":10},
{"Header":"2","Apples":10, "Oranges":153},
{"Header":"3","Oranges":280, "Pears":200},
{"Header":"4","Oranges":1165}
]
const properties = [...new Set(arr.map(e => Object.keys(e)).flat())]
const result = arr.map(e => (properties.forEach(f => !e.hasOwnProperty(f) ? e[f] = 0 : ''), e))
console.log(result)
This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 1 year ago.
I have this array of objects, my aim is to remove dublicate values from values array, I want the result to be [{name:'test1', values:['35,5', '35,2','35,3']}, {name:'test2', values:['33,2', '34,3', '32,5']}]
I have tried following solution but it does not works, Do you have any suggestions? Thanks in advance
let arr = [{name:'test1', values:['35,5', '35,2', '35,2', '35,3', '35,5']},
{name:'test2', values:['35,1', '35,1', '33,2', '34,3', '32,5']}]
let uniqueArray = arr.values.filter(function(item, pos) {
return arr.values.indexOf(item.values) == pos;
})
console.log(uniqueArray)
}
}
You can easily remove duplicates from an Array by creating a new Set based off it.
Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection
If you want the result in an array, just use spread syntax for that, for example:
let arr = [{
name: 'test1',
values: ['35,5', '35,2', '35,2', '35,3', '35,5']
},
{
name: 'test2',
values: ['35,1', '35,1', '33,2', '34,3', '32,5']
}
];
const uniqueArr = arr.reduce((accum, el) => {
// Copy all the original object properties to a new object
const obj = {
...el
};
// Remove the duplicates from values by creating a Set structure
// and then spread that back into an empty array
obj.values = [...new Set(obj.values)];
accum.push(obj);
return accum;
}, []);
uniqueArr.forEach(el => console.dir(el));
This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
How to remove all duplicates from an array of objects?
(77 answers)
Remove duplicate values from an array of objects in javascript [duplicate]
(6 answers)
Closed 3 years ago.
Duplicate values are being storing into an array of object
Based on the given userID need to out the duplicate userId,
if it exist do nothing, else push that userIdinto the teamSocketsList array
But with the below piece of code duplicate values are being stored into an array teamSocketsList
var TeamUser = {
userId : userID,
socketId : socket.id
}
var i = $.inArray( userID, teamSocketsList );
if(i == -1){
teamSocketsList.push(TeamUser);
}else{
teamSocketsList = jQuery.grep(teamSocketsList, function(value) {
return value != userID;
});
}
Actual Result:
[
{"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
{"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
]
Expected Result:
[
{"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
]
Edit:
Here I'm expecting userID to be pushed in to an array teamSocketsList based on the condition, if at all the given userID matches in the present list should return false or do nothing. Otherwise, (iff, it's not at all included then) store it into an array with the auto-generated socketId value
The logic which I had tried to implement was to check whether if that array is empty or not and then, traverse all the elements in the array list so that whenever userID were given as an input it must check the condition and then push that element.
Based on the present answers put up, it'll store the duplicate values and then sort it on and assign it back to teamSocketsList, that's fine.
Along with already mentioned values/reduce, you can take advantage of Set():
const myArray = [
{"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
{"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
]
const unique = (arr, key) => {
const keys = new Set();
return arr.filter(el => !keys.has(el[key]) && keys.add(el[key]));
};
console.log(unique(myArray, "userId"));
In opposition to other response I can point out that with this method is easier to change array and key without adding code.
use reduce along with Object.values. create an object whose keys are userId. If the key does not exist, create the key and then use Object.values to get the required ouput.
const input = [
{"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
{"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
];
const output = Object.values(input.reduce((accu, {userId, socketId}) => {
if(!accu[userId]) accu[userId] = {userId, socketId};
return accu;
}, {}));
console.log(output);
How about this function where you pass in your array and the key to get your result
const convertArrayToObjecByID = ({ array, key }) =>
array.reduce((obj, item) => {
return { ...obj, [item[key]]: item };
}, {})
const input = [
{"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
{"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
]
const myObject = convertArrayToObjecByID({ array:input, key:'userId' })
console.log({myObject})
//then if you want it as an array
console.log(Object.keys(myObject).map(item => myObject[item]))
You can store your data in the object (key-value pair) and avoid adding duplicate data.
For example:
var teamSocketsList = {};
var TeamUser = {
userId : userID,
socketId : socket.id
}
teamSocketsList[TeamUser.userId] = TeamUser;
Then if you are adding new user to teamSocketsList, you can easily (without iterating through all elements in the array) check if there are teamUser with that id.
if(teamSocketsList[TeamUser.userId]) // team user exists in the list
This question already has answers here:
Strange behavior of an array filled by Array.prototype.fill()
(9 answers)
Closed 3 years ago.
I am trying to create an array which has a defined length and fill it with empty arrays. I've tried using all possibilities given by #stpoa's answer here but my array does not behave correctly.
Given the code (I simplified it for the sake of example):
const tasksArray = Array(3).fill([])
const tasksArray2 = [[], [], []]
const tasks = ['task1', 'task2']
const fillWithData = (array) => {
tasks.forEach(task => {
array[0].push(task)
})
}
Gives me an incorrect output for tasksArray and a obviously a correct one for tasksArray2 which is hardcoded
fillWithData(tasksArray) // [['task1', 'task2'], ['task1', 'task2'], ['task1', 'task2']] => not OK, duplicates values!
fillWithData(tasksArray2) // [['task1', 'task2'], [], []] => that's OK
In taskArray, the [] you are using is passed as a reference, and the elements in taskArray all reference the same array.
In taskArray2, you have three separate empty arrays, [], each with their own reference. Therefore you do not get duplicated values.
If you wish to create an array of empty arrays programmatically, use Array.from -
const fillEmptyArrays = (count) =>
Array.from(Array(count), _ => [])
const tasks =
fillEmptyArrays(3)
console.log(tasks)
// [ [], [], [] ]
And please don't include type names like Array in your variable names tasksArray; just name it tasks. JavaScript is a dynamically-typed language and this kind of thinking hurts you in the long run.
You need to get independent object references inside of the array, instead of having literally the constant value.
By taking Array.from with an object with a length property and the build in mapping function, you could get an array of independent arrays.
const tasksArray = Array.from({ length: 3 }, _ => [])
const tasks = ['task1', 'task2']
const fillWithData = (array) => {
tasks.forEach(task => {
array[0].push(task)
})
};
fillWithData(tasksArray);
console.log(tasksArray);
fill puts the value you pass it at each index of the array.
So tasksArray has three references to the same array, while tasksArray2 has a reference to each of three different arrays.
If you want to put three different arrays in there, then you need to explicitly create three arrays.
You could approach it with a counter:
const tasksArray2 = [];
let count = 3;
while (count--) {
tasksArray2.push([]);
}