How to get distinct values from an array of objects in JavaScript?
If this were PHP I'd build an array with the keys and take array_keys
at the end, but JS has no such luxury. Instead, try this:
var flags = [], output = [], l = array.length, i;
for( i=0; i<l; i++) {
if( flags[array[i].age]) continue;
flags[array[i].age] = true;
output.push(array[i].age);
}
Create array of unique objects by property
I'd probably use a flags object during the filtering (edit: I wouldn't anymore, see the note at the end of the answer about ES2015's Set
), like this:
var flags = {};
var newPlaces = places.filter(function(entry) {
if (flags[entry.city]) {
return false;
}
flags[entry.city] = true;
return true;
});
That uses Array#filter
from ECMAScript5 (ES5), which is one of the ES5 additions that can be shimmed (search for "es5 shim" for several options).
You can do it without filter
, of course, it's just a bit more verbose:
var flags = {};
var newPlaces = [];
var index;
for (index = 0; index < places.length; ++index) {
if (!flags[entry.city]) {
flags[entry.city] = true;
newPlaces.push(entry);
}
});
Both of the above assume the first object with a given city should be kept, and all other discarded.
Note: As user2736012 points out below, my test if (flags[entry.city])
will be true for cities with names that happen to be the same as properties that exist on Object.prototype
such as toString
. Very unlikely in this case, but there are four ways to avoid the possibility:
(My usual preferred solution) Create the object without a prototype:
var flags = Object.create(null);
. This is a feature of ES5. Note that this cannot be shimmed for obsolete browsers like IE8 (the single-argument version ofObject.create
can be except when that argument's value isnull
).Use
hasOwnProperty
for the test, e.g.if (flags.hasOwnProperty(entry.city))
Put a prefix on that you know doesn't exist for any
Object.prototype
property, such asxx
:var key = "xx" + entry.city;
if (flags[key]) {
// ...
}
flags[key] = true;As of ES2015, you could use a
Set
instead:const flags = new Set();
const newPlaces = places.filter(entry => {
if (flags.has(entry.city)) {
return false;
}
flags.add(entry.city);
return true;
});
How to get unique values from Object Array Javascript
Try this code it returns unique objects only.
var data = [
{name:"Joe", date:'2018-07-01', amt:250 },
{name:"Mars", date:'2018-07-01', amt:250 },
{name:"Joe", date:'2018-07-02', amt:250 },
{name:"Saturn", date:'2018-07-01', amt:250 },
{name:"Joe", date:'2018-07-02', amt:250 },
{name:"Jupiter", date:'2018-07-01', amt:250 },
]
var resArr = [];
data.filter(function(item){
var i = resArr.findIndex(x => (x.name == item.name && x.date == item.date && x.amt == item.amt));
if(i <= -1){
resArr.push(item);
}
return null;
});
console.log(resArr)
Do tell me if this is not what you're looking for.
How to return an array of unique objects based on the id of the object in es6?
Another one solution:
const arr = [{ id: 1, name: "PrimShal01", period: 3},{ id: 61, name: "TertDeep01", period: 1},{ id: 37, name: "SecoDeep01", period: 2},{ id: 49, name: "TertShal01", period: 1},{ id: 13, name: "PrimDeep01", period: 3},{ id: 61, name: "TertDeep01", period: 1}]
const result = Object.values(
arr.reduce((acc, obj) => ({ ...acc, [obj.id]: obj }), {})
);
console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}
Filter array to unique objects by object.property
The objects in your array are all different objects, even if some happen to have properties with the same values. The .indexOf()
function is comparing references, not property values.
Also, in practice, none of the three objects have identical properties because they all have a different .capture
value.
Use .findIndex()
instead of .indexOf()
, so that you can compare the properties to find matching objects:
objects.filter((value, index, self) => {
return self.findIndex(v => v.actor.name === value.actor.name) === index;
})
Here I'm just using the .actor.name
property, but of course you could compare additional properties if needed.
(Note that .findIndex()
is an ES6 function, but I assume that's fine given that your code is already using arrow functions. Or you can polyfill it.)
var objects = [{ actor: { account: null, degraded: false, mbox: null, mbox_sha1sum: "843c56da78f9eb888274d2d4e12ab1d748ec46234", name: "name", openid: null }, capture: 'value' }, { actor: { account: null, degraded: false, mbox: null, mbox_sha1sum: "843c56da78f9eb888274d2d4e12ab1d748ec12345", name: "name2", openid: null }, capture: 'value2' }, { actor: { account: null, degraded: false, mbox: null, mbox_sha1sum: "843c56da78f9eb888274d2d4e12ab1d748ec46234", name: "name", openid: null }, capture: 'value3' }];
objects.filter((value, index, self) => { return self.findIndex(v => v.actor.name === value.actor.name) === index;}).map(ele => { console.log(ele.capture);});
How to get all unique objects (with two values) in an array?
We can use Array.reduce(),
along with a Map to get the required result.
We'd add each item to the map, using the concatenated x and y values as keys, then return the values() to get de-duplicated values.
This will have complexity of O(n), so it will be efficient for large arrays.
const coords = [{x: 260, y: 60}, {x: 180, y: 0}, {x: 180, y: 240}, {x: 360, y: 120}, {x: 180, y: 60}, {x: 180, y: 60}, {x: 180, y: 60}];
const dedup = [...coords.reduce((map, { x, y }) => {
return (map.set(`${x}-${y}`, { x, y }));
}, new Map()).values()];
console.log('De-duplicated:', dedup)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Getting unique objects from object of array based on property value in Javascript
I've found your solution. Try this:
const getData = () => {
const debtSums = data.map(person => {
const personD = data.filter(el => el.Name === person.Name).reduce((prev, curr) => {
const debt = prev.debt + curr.debt;
return {...person, debt};
})
return personD;
})
const removeDuplicates = debtSums.reduce((prev, curr) => {
const alreadyPushedIndex = prev.findIndex(i => i.Name === curr.Name);
if (alreadyPushedIndex === -1) {
prev.push(curr);
}
return prev;
}, []);
return removeDuplicates;
}
Maybe it could be a bit more optimised but it does what you want :)
Group array of object base on one unique property?
I'm performing an reduce
on the array and it gives me an object in the form of
{
1: [object Set] { ... },
2: [object Set] { ... },
3: [object Set] { ... }
}
where Set
is used to keep unique values only.
After that I'm running a map
on Object.entries
to get the data to the format you wanted.
const items = [{ id: 1, name: 'a' },{ id: 2, name: 'b' },{ id: 3, name: 'c' },{ id: 1, name: 'd' },{ id: 3, name: 'f' },{ id: 1, name: 'a' },{ id: 3, name: 'c' },];
const a = items.reduce((acc,curr)=> {
if(!acc[curr.id]){
acc[curr.id] = new Set();
}
acc[curr.id].add(curr.name)
return acc;
},{})
let result = Object.entries(a).map((el) => ({id: el[0],names:[...el[1]]}))
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Filter unique values from an array of objects
I think forEach()
is better to achieve what you are looking for:
var data=[{id: 555, name: "Sales", person: "Jordan" },{id: 555, name: "Sales", person: "Bob" },{id: 555, name: "Sales", person: "John" },{id: 777, name: "Accounts Payable", person: "Rhoda" },{id: 777, name: "Accounts Payable", person: "Harry" },{id: 888, name: "IT", person: "Joe" },{id: 888, name: "IT", person: "Jake" },];var resArr = [];data.forEach(function(item){ var i = resArr.findIndex(x => x.name == item.name); if(i <= -1){ resArr.push({id: item.id, name: item.name}); }});console.log(resArr);
Related Topics
Http Status Code 401 Even Though I'm Sending Credentials in the Request
Parse Large JSON File in Nodejs
What's the Fastest Way to Convert String to Number in JavaScript
Regex to Check Whether a String Contains Only Numbers
How to Display Pie Chart Data Values of Each Slice in Chart.Js
Create a Simple 10 Second Countdown
Removing Page Title and Date When Printing Web Page (With CSS)
Reading from Udp Port in Browser
Onclick Calling Hide-Div Function Not Working
Why Is It Object.Defineproperty() Rather Than This.Defineproperty() (For Objects)
How to Avoid Long Nesting of Asynchronous Functions in Node.Js
Window.Open(Url, '_Blank'); Not Working on Imac/Safari
How to Check If Page Exists Using JavaScript
How Does Shallow Compare Work in React
How to Return a View from an Ajax Call in Laravel 5
Closing Websocket Correctly (Html5, JavaScript)
Howto: Div with Onclick Inside Another Div with Onclick JavaScript