using ramda group by property and sum results on specified property - javascript

I need help transforming an array of objects using ramda; I'd like to
group by a specified property
sum another property on the
resulting set
given an array like this:
var arr = [
{
title: "scotty",
age: 22,
score: 54,
hobby: "debugging"
}, {
title: "scotty",
age: 22,
score: 19,
hobby: "debugging"
}
, {
title: "gabriel",
age: 40,
score: 1000
}
];
if I want to group by title and sum on age it should return the following summary of values
var arr = [
{
title: "scotty",
age: 44,
hobby: "debugging",
}
, {
title: "gabriel",
age: 40,
score: 1000
}
];
when the unspecified property's differ in value they should be omitted, but if unspecified property's are the same in value it should remain in the final result.
** My Solution **
/*
* [Student]
*/
var arr = [
{
title: "scotty",
age: 22,
score: 54,
hobby: "debugging"
}, {
title: "scotty",
age: 22,
score: 19,
hobby: "debugging"
}
, {
title: "gabriel",
age: 40,
score: 1000
}
];
/*
* String -> [[Student]] -> [Student]
*/
var sumOnProperty = function(property, v){
var sum = (x,y) => x[property] + y[property];
var new_array = [];
v.forEach(arr => {
if(arr.length > 1){
arr[0]["age"] = arr.reduce(sum)
new_array.push(arr[0]);
} else {
if(arr.length != 0){
new_array.push(arr[0]);
}
}
})
return new_array;
}
/*
* String -> String -> [Student] -> [Student]
*/
var groupsumBy = function(groupproperty, sumproperty, arr){
// create grouping
var grouping = R.groupBy(R.prop(groupproperty), arr)
// convert grouping object to array
var result1 = R.valuesIn(grouping);
// sum each grouping and flatten 2d array
var result2 = sumOnProperty(sumproperty, result1);
return result2;
}
groupsumBy("title","age",arr);

To fix your groupBy problem you need to see that groupBy takes a key-generation function function and not a binary predicate.
So, for instance,
const byTitle = R.groupBy(R.prop('title'));
This should get you through your current block. If you need help with the summation, let me know.
Update:
You asked for my approach. It does differ from yours a fair bit. I would probably do something like this:
const sumBy = prop => vals => reduce(
(current, val) => evolve({[prop]: add(val[prop])}, current),
head(vals),
tail(vals)
)
const groupSumBy = curry((groupOn, sumOn, vals) =>
values(map(sumBy(sumOn))(groupBy(prop(groupOn), vals)))
)
groupSumBy('title', 'age', people)
Or if I wanted it a little more concise, I might switch to:
const sumBy = prop => lift(
reduce((current, val) => evolve({[prop]: add(val[prop])}, current)
))(head, tail)
Note that sumBy is relatively reusable. It's not perfect, because it would fail on an empty list. But in our case, we know that the output of groupBy will never create such an empty list for a key. And any version which didn't fail on an empty list would need a way to supply the default case. It simply gets ugly.
You can see this in action on the Ramda REPL.
You could probably make a more easily readable version of groupSumBy using pipe or compose if you were willing to call first with the groupOn and sumOn values, then call the resulting function with the values, that is, if the invocation looked like this:
groupSumBy('title', 'age')(people)
// or more likely:
const foo = groupSumBy('title', age)
foo(people)
But I leave that as an exercise for the reader.

using ramda group by property and sum results on specified property
One option is to reduceBy as follows:
import * as R from "ramda";
const arr = [
{
title: "scotty",
age: 22,
score: 54,
hobby: "debugging"
}, {
title: "scotty",
age: 22,
score: 19,
hobby: "debugging"
}
, {
title: "gabriel",
age: 40,
score: 1000
}
];
const reduction =
R.reduceBy((acc, next) => acc + next.age, 0, (x) => x.title, arr);
console.log(JSON.stringify(reduction, undefined, 2));
The output has grouped by title and has summed the age.
{
"scotty": 44,
"gabriel": 40
}

Related

Trying to apply filter and reduce on an array to sum only numbers

I'm trying to write a function that will be called with an array that has information on a person such as their name and then age. I need this function to grab all of the numbers only and then return them then add them all together but I'm having trouble figuring out how to combine filter and reduce (if that's what I even need to use to do this in the easiest way?) so if you could help with that I would be thankful.
Maybe it would be easier for me not to use an arrow function but I just learned about them an hour ago and wanted to try them out.
Apologies for any typos/wrong jargon as my dyslexia gets the better of me sometimes.
What I've got so far;
const totalNums = arr => arr.reduce((a,b) => a + b, 0)
An example of what I want it to return when the function is supplied with the array is
{ name: 'Clarie', age: 22 },
{ name: 'Bobby', age: 30 },
{ name: 'Antonio', age: 40 },
// returns 92
EDIT
Why isn't the array I'm calling this function with working? Can you provide me a working example without the array being hardcoded like the other answers? - I'm passing in an array to the function. The main objective is to grab any number from the passed in array and add them together with an empty array returning 0.
function totalNums(person) {
person.reduce((a,b) => a + b, 0)
return person.age;
}
console.log(totalNums([]))
The first argument in a reduce callback is the "accumulator" - something that takes the initial value and is then passed into each iteration. The second value is the item that's next in the iteration whether that's a number, a string, an object etc.
In your example you're iterating over an array of objects, so you must perform the sum operation using the age value of each of those objects.
const arr = [
{ name: 'Clarie', age: 22 },
{ name: 'Bobby', age: 30 },
{ name: 'Antonio', age: 40 }
];
const total = arr.reduce((acc, obj) => {
return acc + obj.age;
}, 0);
console.log(total);
You can reduce the object array number as below
const objArr = [
{ name: "Clarie", age: 22 },
{ name: "Bobby", age: 30 },
{ name: "Antonio", age: 40 },
];
console.log(objArr.reduce((prev, curr) => prev + curr.age, 0));
If you want to convert the array of object into array containing only ages:
const objArr = [
{ name: 'Clarie', age: 22 },
{ name: 'Bobby', age: 30 },
{ name: 'Antonio', age: 40 },
];
console.log(objArr.map(obj => obj.age));

How to return specific values from an array with objects inside in a new array which must pass a test?

Hello I am try to get the solution but dont find the right answer on my own research and hope somebody can help me with my problem. The task required that I must write a function which returns every persons name which is 16 or older in a new array. The goal is to write a function which returns in my example: ['Jane', 'Jack']
function onlyAdult(obj) {
}
const examplePeopleArray = [
{ name: 'John', age: 15 },
{ name: 'Jane', age: 16 },
{ name: 'Jack', age: 17 }
];
console.log(onlyAdult(examplePeopleArray));
I tried to manage the task with a for loop which loop through the array and connected a if statement but this way it doesnt worked. After this i tried to find the right methods for my task with every(),filter(), forEach(), map(), some() but none of these actually worked for my task .
function onlyAdult(obj) {
for (i = 0; i < obj.length; i++) {
if (obj[0].age >= 16) {
return obj[0].age;
} else if (obj[1].age >= 16) {
return obj[1].age;
} else if (obj[2].age >= 16) {
return obj[2].age;
}
}
}
I know my code is wrong and also the way I tried to solved it, I would be very grateful when someone could help me .
You can filter the array first using .filter() and then use .map() to get the desired property values only.
const data = [
{ name: 'John', age: 15 },
{ name: 'Jane', age: 16 },
{ name: 'Jack', age: 17 }
];
const result = data.filter(({ age }) => age >= 16).map(({ name }) => name);
console.log(result);
References:
Array.prototype.filter()
Array.prototype.map()
Object Destructuring
const examplePeopleArray = [
{ name: 'John', age: 15 },
{ name: 'Jane', age: 16 },
{ name: 'Jack', age: 17 }
];
const result = examplePeopleArray.reduce((arr, el) => {
if (el.age >= 16) arr.push(el.name)
return arr
}, [])
For this given task reduce will be enough. Here we reduce input array to an array of filtered string values based on age comparison. If age is under 16 we just do not push anything and skip to the next element.

How do I transform an array to hold data based on a value in the data?

I have seen some questions that might look similar but none is the solution in my case. I want to regroup and recreate my array the way that it is arranged or grouped based on one of my values(age). I want to have all data of the same "age" in one place. So here is my sample array:
[
{
"age": 15,
"person": {
name: 'John',
hobby: 'ski'
},
},
{
"age": 23,
"person": {
name: 'Suzi',
hobby: 'golf'
},
},
{
"age": 23,
"person": {
name: 'Joe',
hobby: 'books'
}
},{
"age": 25,
"person": {
name: 'Rosi',
hobby: 'books'
}
},{
"age": 15,
"person": {
name: 'Gary',
hobby: 'books'
}
},
{
"age": 23,
"person": {
name: 'Kane',
hobby: 'books'
}
}
]
And I need to have an array that kind of have age as a key and person as value, so each key could have multiple values meaning the value will kind of be an array itself.
I have read this and this questions and many more but they were not exactly the same.
I feel like I need to use reduce to count duplicate ages and then filter it based on that but how do I get the values of those ages?
EIDT:
Sorry for not being clear:
This is what I need:
{
23: [
{ name: 'Suzi', hoby: 'golf' },
{ name: 'Joe', hobby: 'books'}
],
15: [
{ name: 'Gary', hobby: 'books' }
] ,
.
.
.
}
You're actually going to want to reduce, not filter. Filtering an Array means to remove elements and place the kept elements into a new container. Reducing an array means to transform it into a single value in a new container. Mapping an array means to transform every value in place to a new container. Since you want to change how the data is represented that's a Reduction, from one form to another more condensed form.
Assume your Array of values is stored in let people = [...]
let peopleByAge = people.reduce(function (accumulator, value, index, array){
// The first time through accumulator is the passed extra Object after this function
// See the MDN for Array.prototype.reduce() for more information
if (accumulator[value.age] == undefined){
accumulator[value.age] = [];
}
accumulator[value.age].push(value);
return accumulator
}, {})
console.log(peopleByAge) // { 23: [{ age: 23, name: ..., hobby: ...}, ...], 13: [...], ...}
You can find the MDN article for Array#reduce() here
Thanks to #RobertMennell who patiently answered me and I voted as answer. But I just wanted to write my version which MDN had a great example of. It is a longer version assuming the people is the array name:
const groupedByvalue = 'age';
const groupedArray = people;
const groupBy = (peopleArray, value) => {
return peopleArray.reduce((acc, obj) => {
const key = obj[value];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
console.log(groupBy(groupedArray,groupedByvalue));
Update:
More polished using ternary operator:
const groupedByvalue = 'age';
const groupedArray = people;
const groupBy = (peopleArray, value) => {
return peopleArray.reduce((acc, obj) => {
const key = obj[value];
(!acc[key]) ? (acc[key] = []) : (acc[key].push(obj))
return acc;
}, {});
}
console.log(groupBy(groupedArray,groupedByvalue));

get values from list of objects in javascript [duplicate]

I want to cycle through the objects contained in an array and change the properties of each one. If I do this:
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j]);
}
The console should bring up every object in the array, right? But in fact it only displays the first object. if I console log the array outside of the loop, all the objects appear so there's definitely more in there.
Anyway, here's the next problem. How do I access, for example Object1.x in the array, using the loop?
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j.x]);
}
This returns "undefined." Again the console log outside the loop tells me that the objects all have values for "x". How do I access these properties in the loop?
I was recommended elsewhere to use separate arrays for each of the properties, but I want to make sure I've exhausted this avenue first.
Thank you!
Use forEach its a built-in array function. Array.forEach():
yourArray.forEach(function (arrayItem) {
var x = arrayItem.prop1 + 2;
console.log(x);
});
Some use cases of looping through an array in the functional programming way in JavaScript:
1. Just loop through an array
const myArray = [{x:100}, {x:200}, {x:300}];
myArray.forEach((element, index, array) => {
console.log(element.x); // 100, 200, 300
console.log(index); // 0, 1, 2
console.log(array); // same myArray object 3 times
});
Note: Array.prototype.forEach() is not a functional way strictly speaking, as the function it takes as the input parameter is not supposed to return a value, which thus cannot be regarded as a pure function.
2. Check if any of the elements in an array pass a test
const people = [
{name: 'John', age: 23},
{name: 'Andrew', age: 3},
{name: 'Peter', age: 8},
{name: 'Hanna', age: 14},
{name: 'Adam', age: 37}];
const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true
3. Transform to a new array
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]
Note: The map() method creates a new array with the results of calling a provided function on every element in the calling array.
4. Sum up a particular property, and calculate its average
const myArray = [{x:100}, {x:200}, {x:300}];
const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300
const average = sum / myArray.length;
console.log(average); // 200
5. Create a new array based on the original but without modifying it
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => {
return {
...element,
x: element.x * 2
};
});
console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]
6. Count the number of each category
const people = [
{name: 'John', group: 'A'},
{name: 'Andrew', group: 'C'},
{name: 'Peter', group: 'A'},
{name: 'James', group: 'B'},
{name: 'Hanna', group: 'A'},
{name: 'Adam', group: 'B'}];
const groupInfo = people.reduce((groups, person) => {
const {A = 0, B = 0, C = 0} = groups;
if (person.group === 'A') {
return {...groups, A: A + 1};
} else if (person.group === 'B') {
return {...groups, B: B + 1};
} else {
return {...groups, C: C + 1};
}
}, {});
console.log(groupInfo); // {A: 3, C: 1, B: 2}
7. Retrieve a subset of an array based on particular criteria
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}]
Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.
8. Sort an array
const people = [
{ name: "John", age: 21 },
{ name: "Peter", age: 31 },
{ name: "Andrew", age: 29 },
{ name: "Thomas", age: 25 }
];
let sortByAge = people.sort(function (p1, p2) {
return p1.age - p2.age;
});
console.log(sortByAge);
9. Find an element in an array
const people = [ {name: "john", age:23},
{name: "john", age:43},
{name: "jim", age:101},
{name: "bob", age:67} ];
const john = people.find(person => person.name === 'john');
console.log(john);
The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.
References
Array.prototype.some()
Array.prototype.forEach()
Array.prototype.map()
Array.prototype.filter()
Array.prototype.sort()
Spread syntax
Array.prototype.find()
You can use a for..of loop to loop over an array of objects.
for (let item of items) {
console.log(item); // Will display contents of the object inside the array
}
One of the best things about for..of loops is that they can iterate over more than just arrays. You can iterate over any type of iterable, including maps and objects. Make sure you use a transpiler or something like TypeScript if you need to support older browsers.
If you wanted to iterate over a map, the syntax is largely the same as the above, except it handles both the key and value.
for (const [key, value] of items) {
console.log(value);
}
I use for..of loops for pretty much every kind of iteration I do in Javascript. Furthermore, one of the coolest things is they also work with async/await as well.
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
Here's an example on how you can do it :)
var students = [{
name: "Mike",
track: "track-a",
achievements: 23,
points: 400,
},
{
name: "james",
track: "track-a",
achievements: 2,
points: 21,
},
]
students.forEach(myFunction);
function myFunction(item, index) {
for (var key in item) {
console.log(item[key])
}
}
Looping through an array of objects is a pretty fundamental functionality. This is what works for me.
var person = [];
person[0] = {
firstName: "John",
lastName: "Doe",
age: 60
};
var i, item;
for (i = 0; i < person.length; i++) {
for (item in person[i]) {
document.write(item + ": " + person[i][item] + "<br>");
}
}
It's really simple using the forEach method since ES5+. You can directly change each property of each object in your array.
myArray.forEach(function (arrayElem){
arrayElem = newPropertyValue;
});
If you want to access a specific property on each object:
myArray.forEach(function (arrayElem){
arrayElem.nameOfYourProperty = newPropertyValue;
});
myArray[j.x] is logically incorrect.
Use (myArray[j].x); instead
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
const jobs = [
{
name: "sipher",
family: "sipherplus",
job: "Devops"
},
{
name: "john",
family: "Doe",
job: "Devops"
},
{
name: "jim",
family: "smith",
job: "Devops"
}
];
const txt =
` <ul>
${jobs.map(job => `<li>${job.name} ${job.family} -> ${job.job}</li>`).join('')}
</ul>`
;
document.body.innerHTML = txt;
Be careful about the back Ticks (`)
this.data = [{name:"Rajiv", city:"Deoria"},{name:"Babbi", city:"Salempr"},{name:"Brijesh", city:"GKP"}];
for(const n of this.data) {
console.log(n.name)
}
This would work. Looping thorough array(yourArray) . Then loop through direct properties of each object (eachObj) .
yourArray.forEach( function (eachObj){
for (var key in eachObj) {
if (eachObj.hasOwnProperty(key)){
console.log(key,eachObj[key]);
}
}
});
Accepted answer uses normal function. So posting the same code with slight modification using arrow function on forEach
yourArray.forEach(arrayItem => {
var x = arrayItem.prop1 + 2;
console.log(x);
});
Also in $.each you can use arrow function like below
$.each(array, (item, index) => {
console.log(index, item);
});
Here's another way of iterating through an array of objects (you need to include jQuery library in your document for these).
$.each(array, function(element) {
// do some operations with each element...
});
Array object iteration, using jQuery,
(use the second parameter to print the string).
$.each(array, function(index, item) {
console.log(index, item);
});
var c = {
myProperty: [
{ name: 'this' },
{ name: 'can' },
{ name: 'get' },
{ name: 'crazy' }
]
};
c.myProperty.forEach(function(myProperty_element) {
var x = myProperty_element.name;
console.log('the name of the member is : ' + x);
})
This is one of the ways how I was able to achieve it.
I want to loop and deconstruction assignment at the same time, so code like this: config.map(({ text, callback })=>add_btn({ text, callback }))
This might help somebody. Maybe it's a bug in Node.
var arr = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
var c = 0;
This doesn't work:
while (arr[c].name) { c++; } // TypeError: Cannot read property 'name' of undefined
But this works...
while (arr[c]) { c++; } // Inside the loop arr[c].name works as expected.
This works too...
while ((arr[c]) && (arr[c].name)) { c++; }
BUT simply reversing the order does not work. I'm guessing there's some kind of internal optimization here that breaks Node.
while ((arr[c].name) && (arr[c])) { c++; }
Error says the array is undefined, but it's not :-/ Node v11.15.0
I know it's been long but for anyone else encountering this issue, my problem is that I was looping through an array of arrays containing only one array. Like this:
// array snippet (returned from here)
} else {
callback([results])
}
And I was using the array like this
for(const result of results){
console.log(result.x)
}
As you can see, the array I wanted to iterate over was actually inside another array. removing the square brackets helped. Node JS and MySQL.

How to find duplicate values in a JavaScript array of objects, and output only unique values?

I'm learning JS. Supposing I have the below array of objects:
var family = [
{
name: "Mike",
age: 10
},
{
name: "Matt"
age: 13
},
{
name: "Nancy",
age: 15
},
{
name: "Adam",
age: 22
},
{
name: "Jenny",
age: 85
},
{
name: "Nancy",
age: 2
},
{
name: "Carl",
age: 40
}
];
Notice that Nancy is showing up twice (changing only the age). Supposing I want to output only unique names. How do I output the above array of objects, without duplicates? ES6 answers more than welcome.
Related (couldn't find a good way for usage on objects):
Remove Duplicates from JavaScript Array
Easiest way to find duplicate values in a JavaScript array
EDIT Here's what I tried. It works well with strings but I can't figure how to make it work with objects:
family.reduce((a, b) => {
if (a.indexOf(b) < 0 ) {
a.push(b);
}
return a;
},[]);
You could use a Set in combination with Array#map and a spread operator ... in a single line.
Map returns an array with all names, which are going into the set initializer and then all values of the set are returned in an array.
var family = [{ name: "Mike", age: 10 }, { name: "Matt", age: 13 }, { name: "Nancy", age: 15 }, { name: "Adam", age: 22 }, { name: "Jenny", age: 85 }, { name: "Nancy", age: 2 }, { name: "Carl", age: 40 }],
unique = [...new Set(family.map(a => a.name))];
console.log(unique);
For filtering and return only unique names, you can use Array#filter with Set.
var family = [{ name: "Mike", age: 10 }, { name: "Matt", age: 13 }, { name: "Nancy", age: 15 }, { name: "Adam", age: 22 }, { name: "Jenny", age: 85 }, { name: "Nancy", age: 2 }, { name: "Carl", age: 40 }],
unique = family.filter((set => f => !set.has(f.name) && set.add(f.name))(new Set));
console.log(unique);
The Solution
Store occurrences of name external to the loop in an object, and filter if there's been a previous occurrence.
https://jsfiddle.net/nputptbb/2/
var occurrences = {}
var filteredFamily = family.filter(function(x) {
if (occurrences[x.name]) {
return false;
}
occurrences[x.name] = true;
return true;
})
you can also generalize this solution to a function
function filterByProperty(array, propertyName) {
var occurrences = {}
return array.filter(function(x) {
var property = x[propertyName]
if (occurrences[property]) {
return false;
}
occurrences[property]] = true;
return true;
})
}
and use it like
var filteredFamily = filterByProperty(family, 'name')
Explanation
Don't compare objects using indexOf, which only uses the === operator between objects. The reason why your current answer doesn't work is because === in JS does not compare the objects deeply, but instead compares the references. What I mean by that you can see in the following code:
var a = { x: 1 }
var b = { x: 1 }
console.log(a === b) // false
console.log(a === a) // true
Equality will tell you if you found the same exact object, but not if you found an object with the same contents.
In this case, you can compare your object on name since it should be a unique key. So obj.name === obj.name instead of obj === obj. Moreover another problem with your code that affects its runtime and not its function is that you use an indexOf inside of your reduce. indexOf is O(n), which makes the complexity of your algorithm O(n^2). Thus, it's better to use an object, which has O(1) lookup.
This will work fine.
const result = [1, 2, 2, 3, 3, 3, 3].reduce((x, y) => x.includes(y) ? x : [...x, y], []);
console.log(result);
With the code you mentioned, you can try:
family.filter((item, index, array) => {
return array.map((mapItem) => mapItem['name']).indexOf(item['name']) === index
})
Or you can have a generic function to make it work for other array of objects as well:
function printUniqueResults (arrayOfObj, key) {
return arrayOfObj.filter((item, index, array) => {
return array.map((mapItem) => mapItem[key]).indexOf(item[key]) === index
})
}
and then just use printUniqueResults(family, 'name')
(FIDDLE)
I just thought of 2 simple ways for Lodash users
Given this array:
let family = [
{
name: "Mike",
age: 10
},
{
name: "Matt",
age: 13
},
{
name: "Nancy",
age: 15
},
{
name: "Adam",
age: 22
},
{
name: "Jenny",
age: 85
},
{
name: "Nancy",
age: 2
},
{
name: "Carl",
age: 40
}
]
1. Find duplicates:
let duplicatesArr = _.difference(family, _.uniqBy(family, 'name'), 'name')
// duplicatesArr:
// [{
// name: "Nancy",
// age: 2
// }]
2 Find if there are duplicates, for validation purpose:
let uniqArr = _.uniqBy(family, 'name')
if (uniqArr.length === family.length) {
// No duplicates
}
if (uniqArr.length !== family.length) {
// Has duplicates
}
Since most of the answers won't have a good performance, i thought i share my take on this:
const arrayWithDuplicateData = [{ id: 5, name: 'Facebook'}, { id: 3, name: 'Twitter' }, { id: 5, name: 'Facebook' }];
const uniqueObj = {};
arrayWithDuplicateData.forEach(i => {
uniqueObj[i.id] = i;
});
const arrayWithoutDuplicates = Object.values(uniqueObj);
We're leveraging the fact that keys are unique within objects. That means the last duplication item inside the first array, will win over its predecessors. If we'd want to change that, we could flip the array before iterating over it.
Also we're not bound to use only one property of our object for identifying duplications.
const arrayWithDuplicateData = [{ id: 5, name: 'Facebook'}, { id: 3, name: 'Twitter' }, { id: 5, name: 'Facebook' }];
const uniqueObj = {};
arrayWithDuplicateData.forEach(item => {
uniqueObj[`${item.id}_${item.name}`] = item;
});
const arrayWithoutDuplicates = Object.values(uniqueObj);
Or we could simply add a check, if the uniqueObj already holds a key and if yes, not overwrite it.
Overall this way is not very costly in terms of performance and served me well so far.
I would probably set up some kind of object. Since you've said ECMAScript 6, you have access to Set, but since you want to compare values on your objects, it will take a little more work than that.
An example might look something like this (removed namespace pattern for clarity):
var setOfValues = new Set();
var items = [];
function add(item, valueGetter) {
var value = valueGetter(item);
if (setOfValues.has(value))
return;
setOfValues.add(value);
items.push(item);
}
function addMany(items, valueGetter) {
items.forEach(item => add(item, valueGetter));
}
Use it like this:
var family = [
...
];
addMany(family, item => item.name);
// items will now contain the unique items
Explanation: you need to pull a value from each object as it's added and decide if it has already been added yet, based on the value you get. It requires a value getter, which is a function that given an item, returns a value (item => item.name). Then, you only add items whose values haven't already been seen.
A class implementation:
// Prevents duplicate objects from being added
class ObjectSet {
constructor(key) {
this.key = key;
this.items = [];
this.set = new Set();
}
add(item) {
if (this.set.has(item[this.key])) return;
this.set.add(item[this.key]);
this.items.push(item);
}
addMany(items) {
items.forEach(item => this.add(item));
}
}
var mySet = new ObjectSet('name');
mySet.addMany(family);
console.log(mySet.items);

Categories

Resources