Finding multiple objects in an array and adding to count value for that object
I have been toying with the best way to go about doing this and have found some options but not one that preserves the format I am trying to keep for the array/object.
The overview is I have an array that gets random objects pushed into it and there can be duplicates of the same object, but I want to change it so there is only 1 of each object and instead, having a count property for each object.
An example of what I am working with and what I am aiming to have.
arr = [
Name: Item1, Value: 20 ,
Name: Item2, Value: 20 ,
Name: Item1, Value: 20
];
result = [
Name: Item1, Value: 20, Count: 2 ,
Name: Item2, Value: 20, Count: 1
];
As a side note, I am wondering if it better to do this after the array is filled or if it is better to do this while pushing the objects into the array?
javascript arrays reactjs object array.prototype.map
add a comment |
I have been toying with the best way to go about doing this and have found some options but not one that preserves the format I am trying to keep for the array/object.
The overview is I have an array that gets random objects pushed into it and there can be duplicates of the same object, but I want to change it so there is only 1 of each object and instead, having a count property for each object.
An example of what I am working with and what I am aiming to have.
arr = [
Name: Item1, Value: 20 ,
Name: Item2, Value: 20 ,
Name: Item1, Value: 20
];
result = [
Name: Item1, Value: 20, Count: 2 ,
Name: Item2, Value: 20, Count: 1
];
As a side note, I am wondering if it better to do this after the array is filled or if it is better to do this while pushing the objects into the array?
javascript arrays reactjs object array.prototype.map
2
do you want to group byName
andValue
, or only byName
?
– Nina Scholz
Nov 14 '18 at 21:07
Only by name, the values for each of the objects in the array will all be the same anyway.
– Austin
Nov 14 '18 at 21:18
add a comment |
I have been toying with the best way to go about doing this and have found some options but not one that preserves the format I am trying to keep for the array/object.
The overview is I have an array that gets random objects pushed into it and there can be duplicates of the same object, but I want to change it so there is only 1 of each object and instead, having a count property for each object.
An example of what I am working with and what I am aiming to have.
arr = [
Name: Item1, Value: 20 ,
Name: Item2, Value: 20 ,
Name: Item1, Value: 20
];
result = [
Name: Item1, Value: 20, Count: 2 ,
Name: Item2, Value: 20, Count: 1
];
As a side note, I am wondering if it better to do this after the array is filled or if it is better to do this while pushing the objects into the array?
javascript arrays reactjs object array.prototype.map
I have been toying with the best way to go about doing this and have found some options but not one that preserves the format I am trying to keep for the array/object.
The overview is I have an array that gets random objects pushed into it and there can be duplicates of the same object, but I want to change it so there is only 1 of each object and instead, having a count property for each object.
An example of what I am working with and what I am aiming to have.
arr = [
Name: Item1, Value: 20 ,
Name: Item2, Value: 20 ,
Name: Item1, Value: 20
];
result = [
Name: Item1, Value: 20, Count: 2 ,
Name: Item2, Value: 20, Count: 1
];
As a side note, I am wondering if it better to do this after the array is filled or if it is better to do this while pushing the objects into the array?
javascript arrays reactjs object array.prototype.map
javascript arrays reactjs object array.prototype.map
edited Nov 14 '18 at 21:07
ibrahim mahrir
22.2k41949
22.2k41949
asked Nov 14 '18 at 21:04
AustinAustin
395
395
2
do you want to group byName
andValue
, or only byName
?
– Nina Scholz
Nov 14 '18 at 21:07
Only by name, the values for each of the objects in the array will all be the same anyway.
– Austin
Nov 14 '18 at 21:18
add a comment |
2
do you want to group byName
andValue
, or only byName
?
– Nina Scholz
Nov 14 '18 at 21:07
Only by name, the values for each of the objects in the array will all be the same anyway.
– Austin
Nov 14 '18 at 21:18
2
2
do you want to group by
Name
and Value
, or only by Name
?– Nina Scholz
Nov 14 '18 at 21:07
do you want to group by
Name
and Value
, or only by Name
?– Nina Scholz
Nov 14 '18 at 21:07
Only by name, the values for each of the objects in the array will all be the same anyway.
– Austin
Nov 14 '18 at 21:18
Only by name, the values for each of the objects in the array will all be the same anyway.
– Austin
Nov 14 '18 at 21:18
add a comment |
4 Answers
4
active
oldest
votes
If items are continuously being added, you can maintain an "index" (by Name
) of objects you've already added to the array so that whenever a new object is added, you can update the count if it's already present or push it to the array if it's not:
var arr = ;
var index = ;
function addItem(o)
if (o.Name in index)
index[o.Name].Count += 1;
else
index[o.Name] = o;
o.Count = 1;
arr.push(o);
addItem(
Name: 'Item1',
Value: 20
);
addItem(
Name: 'Item2',
Value: 20
);
addItem(
Name: 'Item1',
Value: 20
);
console.log(arr);
The benefit of this approach is that you don't have to recompute counts from scratch (which is an O(n) operation) every time you want to get the result
array.
This doesn't match OPs expected output - he's adding aCount
property, not incrementingValue
– chazsolo
Nov 14 '18 at 21:13
@chazsolo good point. Thank you.
– slider
Nov 14 '18 at 21:14
Thanks for posting this, I was thinking of how to do this beforehand, and have the Count already apart of the object. I never used an index before and had forgotten about it.
– Austin
Nov 15 '18 at 10:51
add a comment |
Assuming the value of each item is the same, you can do a simple forEach loop. For each element, check to see if the object exists in 'result'. If so, increment the count, otherwise add it to the result array.
let result = ;
arr.forEach(item =>
let resObj = result.find(resObj => resObj.Name === item.Name);
resObj ? resObj.Count++ : result.push('Name':item.Name, 'Value': item.Value, 'Count': 1);
);
console.log(result);
In this case, you don't want to use arr.map, since we're not updating the original array.
Thank you, this is just what I was thinking for how to do it, trying to get a good grasp on manipulating an array of objects.
– Austin
Nov 15 '18 at 10:50
add a comment |
You could take a hash table and count same items.
var array = [ Name: 'Item1', Value: 20 , Name: 'Item2', Value: 20 , Name: 'Item1', Value: 20 ],
result = Object.values(array.reduce((r, Name, Value ) => , ));
console.log(result);
.as-console-wrapper max-height: 100% !important; top: 0;
add a comment |
You can loop through the array and maintain 1 temporary object with "Name" as a key, If same name is found increment "count" by 1
let array = [ Name: 'Item1', Value: 20 , Name: 'Item2', Value: 20 , Name: 'Item1', Value: 20 ]
let tempResult =
for (let d of array)
tempResult[d.Name] =
count: 1,
...d,
...(tempResult[d.Name] && count: tempResult[d.Name].count + 1 )
let result = Object.values(tempResult)
console.log(result);
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53308696%2ffinding-multiple-objects-in-an-array-and-adding-to-count-value-for-that-object%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
If items are continuously being added, you can maintain an "index" (by Name
) of objects you've already added to the array so that whenever a new object is added, you can update the count if it's already present or push it to the array if it's not:
var arr = ;
var index = ;
function addItem(o)
if (o.Name in index)
index[o.Name].Count += 1;
else
index[o.Name] = o;
o.Count = 1;
arr.push(o);
addItem(
Name: 'Item1',
Value: 20
);
addItem(
Name: 'Item2',
Value: 20
);
addItem(
Name: 'Item1',
Value: 20
);
console.log(arr);
The benefit of this approach is that you don't have to recompute counts from scratch (which is an O(n) operation) every time you want to get the result
array.
This doesn't match OPs expected output - he's adding aCount
property, not incrementingValue
– chazsolo
Nov 14 '18 at 21:13
@chazsolo good point. Thank you.
– slider
Nov 14 '18 at 21:14
Thanks for posting this, I was thinking of how to do this beforehand, and have the Count already apart of the object. I never used an index before and had forgotten about it.
– Austin
Nov 15 '18 at 10:51
add a comment |
If items are continuously being added, you can maintain an "index" (by Name
) of objects you've already added to the array so that whenever a new object is added, you can update the count if it's already present or push it to the array if it's not:
var arr = ;
var index = ;
function addItem(o)
if (o.Name in index)
index[o.Name].Count += 1;
else
index[o.Name] = o;
o.Count = 1;
arr.push(o);
addItem(
Name: 'Item1',
Value: 20
);
addItem(
Name: 'Item2',
Value: 20
);
addItem(
Name: 'Item1',
Value: 20
);
console.log(arr);
The benefit of this approach is that you don't have to recompute counts from scratch (which is an O(n) operation) every time you want to get the result
array.
This doesn't match OPs expected output - he's adding aCount
property, not incrementingValue
– chazsolo
Nov 14 '18 at 21:13
@chazsolo good point. Thank you.
– slider
Nov 14 '18 at 21:14
Thanks for posting this, I was thinking of how to do this beforehand, and have the Count already apart of the object. I never used an index before and had forgotten about it.
– Austin
Nov 15 '18 at 10:51
add a comment |
If items are continuously being added, you can maintain an "index" (by Name
) of objects you've already added to the array so that whenever a new object is added, you can update the count if it's already present or push it to the array if it's not:
var arr = ;
var index = ;
function addItem(o)
if (o.Name in index)
index[o.Name].Count += 1;
else
index[o.Name] = o;
o.Count = 1;
arr.push(o);
addItem(
Name: 'Item1',
Value: 20
);
addItem(
Name: 'Item2',
Value: 20
);
addItem(
Name: 'Item1',
Value: 20
);
console.log(arr);
The benefit of this approach is that you don't have to recompute counts from scratch (which is an O(n) operation) every time you want to get the result
array.
If items are continuously being added, you can maintain an "index" (by Name
) of objects you've already added to the array so that whenever a new object is added, you can update the count if it's already present or push it to the array if it's not:
var arr = ;
var index = ;
function addItem(o)
if (o.Name in index)
index[o.Name].Count += 1;
else
index[o.Name] = o;
o.Count = 1;
arr.push(o);
addItem(
Name: 'Item1',
Value: 20
);
addItem(
Name: 'Item2',
Value: 20
);
addItem(
Name: 'Item1',
Value: 20
);
console.log(arr);
The benefit of this approach is that you don't have to recompute counts from scratch (which is an O(n) operation) every time you want to get the result
array.
var arr = ;
var index = ;
function addItem(o)
if (o.Name in index)
index[o.Name].Count += 1;
else
index[o.Name] = o;
o.Count = 1;
arr.push(o);
addItem(
Name: 'Item1',
Value: 20
);
addItem(
Name: 'Item2',
Value: 20
);
addItem(
Name: 'Item1',
Value: 20
);
console.log(arr);
var arr = ;
var index = ;
function addItem(o)
if (o.Name in index)
index[o.Name].Count += 1;
else
index[o.Name] = o;
o.Count = 1;
arr.push(o);
addItem(
Name: 'Item1',
Value: 20
);
addItem(
Name: 'Item2',
Value: 20
);
addItem(
Name: 'Item1',
Value: 20
);
console.log(arr);
edited Nov 14 '18 at 21:22
answered Nov 14 '18 at 21:11
sliderslider
8,43311130
8,43311130
This doesn't match OPs expected output - he's adding aCount
property, not incrementingValue
– chazsolo
Nov 14 '18 at 21:13
@chazsolo good point. Thank you.
– slider
Nov 14 '18 at 21:14
Thanks for posting this, I was thinking of how to do this beforehand, and have the Count already apart of the object. I never used an index before and had forgotten about it.
– Austin
Nov 15 '18 at 10:51
add a comment |
This doesn't match OPs expected output - he's adding aCount
property, not incrementingValue
– chazsolo
Nov 14 '18 at 21:13
@chazsolo good point. Thank you.
– slider
Nov 14 '18 at 21:14
Thanks for posting this, I was thinking of how to do this beforehand, and have the Count already apart of the object. I never used an index before and had forgotten about it.
– Austin
Nov 15 '18 at 10:51
This doesn't match OPs expected output - he's adding a
Count
property, not incrementing Value
– chazsolo
Nov 14 '18 at 21:13
This doesn't match OPs expected output - he's adding a
Count
property, not incrementing Value
– chazsolo
Nov 14 '18 at 21:13
@chazsolo good point. Thank you.
– slider
Nov 14 '18 at 21:14
@chazsolo good point. Thank you.
– slider
Nov 14 '18 at 21:14
Thanks for posting this, I was thinking of how to do this beforehand, and have the Count already apart of the object. I never used an index before and had forgotten about it.
– Austin
Nov 15 '18 at 10:51
Thanks for posting this, I was thinking of how to do this beforehand, and have the Count already apart of the object. I never used an index before and had forgotten about it.
– Austin
Nov 15 '18 at 10:51
add a comment |
Assuming the value of each item is the same, you can do a simple forEach loop. For each element, check to see if the object exists in 'result'. If so, increment the count, otherwise add it to the result array.
let result = ;
arr.forEach(item =>
let resObj = result.find(resObj => resObj.Name === item.Name);
resObj ? resObj.Count++ : result.push('Name':item.Name, 'Value': item.Value, 'Count': 1);
);
console.log(result);
In this case, you don't want to use arr.map, since we're not updating the original array.
Thank you, this is just what I was thinking for how to do it, trying to get a good grasp on manipulating an array of objects.
– Austin
Nov 15 '18 at 10:50
add a comment |
Assuming the value of each item is the same, you can do a simple forEach loop. For each element, check to see if the object exists in 'result'. If so, increment the count, otherwise add it to the result array.
let result = ;
arr.forEach(item =>
let resObj = result.find(resObj => resObj.Name === item.Name);
resObj ? resObj.Count++ : result.push('Name':item.Name, 'Value': item.Value, 'Count': 1);
);
console.log(result);
In this case, you don't want to use arr.map, since we're not updating the original array.
Thank you, this is just what I was thinking for how to do it, trying to get a good grasp on manipulating an array of objects.
– Austin
Nov 15 '18 at 10:50
add a comment |
Assuming the value of each item is the same, you can do a simple forEach loop. For each element, check to see if the object exists in 'result'. If so, increment the count, otherwise add it to the result array.
let result = ;
arr.forEach(item =>
let resObj = result.find(resObj => resObj.Name === item.Name);
resObj ? resObj.Count++ : result.push('Name':item.Name, 'Value': item.Value, 'Count': 1);
);
console.log(result);
In this case, you don't want to use arr.map, since we're not updating the original array.
Assuming the value of each item is the same, you can do a simple forEach loop. For each element, check to see if the object exists in 'result'. If so, increment the count, otherwise add it to the result array.
let result = ;
arr.forEach(item =>
let resObj = result.find(resObj => resObj.Name === item.Name);
resObj ? resObj.Count++ : result.push('Name':item.Name, 'Value': item.Value, 'Count': 1);
);
console.log(result);
In this case, you don't want to use arr.map, since we're not updating the original array.
answered Nov 14 '18 at 21:32
Steve ConradSteve Conrad
212
212
Thank you, this is just what I was thinking for how to do it, trying to get a good grasp on manipulating an array of objects.
– Austin
Nov 15 '18 at 10:50
add a comment |
Thank you, this is just what I was thinking for how to do it, trying to get a good grasp on manipulating an array of objects.
– Austin
Nov 15 '18 at 10:50
Thank you, this is just what I was thinking for how to do it, trying to get a good grasp on manipulating an array of objects.
– Austin
Nov 15 '18 at 10:50
Thank you, this is just what I was thinking for how to do it, trying to get a good grasp on manipulating an array of objects.
– Austin
Nov 15 '18 at 10:50
add a comment |
You could take a hash table and count same items.
var array = [ Name: 'Item1', Value: 20 , Name: 'Item2', Value: 20 , Name: 'Item1', Value: 20 ],
result = Object.values(array.reduce((r, Name, Value ) => , ));
console.log(result);
.as-console-wrapper max-height: 100% !important; top: 0;
add a comment |
You could take a hash table and count same items.
var array = [ Name: 'Item1', Value: 20 , Name: 'Item2', Value: 20 , Name: 'Item1', Value: 20 ],
result = Object.values(array.reduce((r, Name, Value ) => , ));
console.log(result);
.as-console-wrapper max-height: 100% !important; top: 0;
add a comment |
You could take a hash table and count same items.
var array = [ Name: 'Item1', Value: 20 , Name: 'Item2', Value: 20 , Name: 'Item1', Value: 20 ],
result = Object.values(array.reduce((r, Name, Value ) => , ));
console.log(result);
.as-console-wrapper max-height: 100% !important; top: 0;
You could take a hash table and count same items.
var array = [ Name: 'Item1', Value: 20 , Name: 'Item2', Value: 20 , Name: 'Item1', Value: 20 ],
result = Object.values(array.reduce((r, Name, Value ) => , ));
console.log(result);
.as-console-wrapper max-height: 100% !important; top: 0;
var array = [ Name: 'Item1', Value: 20 , Name: 'Item2', Value: 20 , Name: 'Item1', Value: 20 ],
result = Object.values(array.reduce((r, Name, Value ) => , ));
console.log(result);
.as-console-wrapper max-height: 100% !important; top: 0;
var array = [ Name: 'Item1', Value: 20 , Name: 'Item2', Value: 20 , Name: 'Item1', Value: 20 ],
result = Object.values(array.reduce((r, Name, Value ) => , ));
console.log(result);
.as-console-wrapper max-height: 100% !important; top: 0;
edited Nov 14 '18 at 21:19
answered Nov 14 '18 at 21:12
Nina ScholzNina Scholz
187k1596172
187k1596172
add a comment |
add a comment |
You can loop through the array and maintain 1 temporary object with "Name" as a key, If same name is found increment "count" by 1
let array = [ Name: 'Item1', Value: 20 , Name: 'Item2', Value: 20 , Name: 'Item1', Value: 20 ]
let tempResult =
for (let d of array)
tempResult[d.Name] =
count: 1,
...d,
...(tempResult[d.Name] && count: tempResult[d.Name].count + 1 )
let result = Object.values(tempResult)
console.log(result);
add a comment |
You can loop through the array and maintain 1 temporary object with "Name" as a key, If same name is found increment "count" by 1
let array = [ Name: 'Item1', Value: 20 , Name: 'Item2', Value: 20 , Name: 'Item1', Value: 20 ]
let tempResult =
for (let d of array)
tempResult[d.Name] =
count: 1,
...d,
...(tempResult[d.Name] && count: tempResult[d.Name].count + 1 )
let result = Object.values(tempResult)
console.log(result);
add a comment |
You can loop through the array and maintain 1 temporary object with "Name" as a key, If same name is found increment "count" by 1
let array = [ Name: 'Item1', Value: 20 , Name: 'Item2', Value: 20 , Name: 'Item1', Value: 20 ]
let tempResult =
for (let d of array)
tempResult[d.Name] =
count: 1,
...d,
...(tempResult[d.Name] && count: tempResult[d.Name].count + 1 )
let result = Object.values(tempResult)
console.log(result);
You can loop through the array and maintain 1 temporary object with "Name" as a key, If same name is found increment "count" by 1
let array = [ Name: 'Item1', Value: 20 , Name: 'Item2', Value: 20 , Name: 'Item1', Value: 20 ]
let tempResult =
for (let d of array)
tempResult[d.Name] =
count: 1,
...d,
...(tempResult[d.Name] && count: tempResult[d.Name].count + 1 )
let result = Object.values(tempResult)
console.log(result);
let array = [ Name: 'Item1', Value: 20 , Name: 'Item2', Value: 20 , Name: 'Item1', Value: 20 ]
let tempResult =
for (let d of array)
tempResult[d.Name] =
count: 1,
...d,
...(tempResult[d.Name] && count: tempResult[d.Name].count + 1 )
let result = Object.values(tempResult)
console.log(result);
let array = [ Name: 'Item1', Value: 20 , Name: 'Item2', Value: 20 , Name: 'Item1', Value: 20 ]
let tempResult =
for (let d of array)
tempResult[d.Name] =
count: 1,
...d,
...(tempResult[d.Name] && count: tempResult[d.Name].count + 1 )
let result = Object.values(tempResult)
console.log(result);
answered Nov 14 '18 at 21:31
Nitish NarangNitish Narang
2,9601815
2,9601815
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53308696%2ffinding-multiple-objects-in-an-array-and-adding-to-count-value-for-that-object%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
do you want to group by
Name
andValue
, or only byName
?– Nina Scholz
Nov 14 '18 at 21:07
Only by name, the values for each of the objects in the array will all be the same anyway.
– Austin
Nov 14 '18 at 21:18