So I have an object array that as follows:
var array = [
{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 },
]
I want to filter data depending if the name
, amount
and date
has duplicate.
This one doesn't filter even a duplicate name.
var unique = array.filter((v, i, a) =>{ return a.indexOf(v) === i});
How can I filter duplicate for this one based on name
, amount
and date
?
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.
Just try this:
var array = [
{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 unique = Array.from(new Set(array.map(JSON.stringify))).map(JSON.parse);
console.log(unique)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With