Get distinct array of objects in javascript - javascript

Distinct array of objects as like below; i want to get unique array of objects.
Example Array:
const data = [ { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "29", project: "Javascript" }, { "name": "abc", age: "31", project: "C++" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }]
Expected Output:
const data = [ { "name": "abc", age: "31", project: "Java" },{ "name": "abc", age: "29", project: "Javascript" }, { "name": "abc", age: "31", project: "C++" }]

This approach enforces a consistent key order, and uses JSON.stringify on each object to test for uniqueness.
const data = [ { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "29", project: "Javascript" }, { "name": "abc", age: "31", project: "C++" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }]
const result = [...new Set(data.map(i=>JSON.stringify(Object.fromEntries(
Object.entries(i).sort(([a],[b])=>a.localeCompare(b))))
))].map(JSON.parse)
console.log(result)

let unique = [...new Set(data.map(i => JSON.stringify(i)))].map(i => JSON.parse(i));

As per your data, project property is containing dynamic values. Hence, You can filtered out the duplicates with in a single line of code by using Array.filter() method.
Live Demo :
const data = [ { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "29", project: "Javascript" }, { "name": "abc", age: "31", project: "C++" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }];
const uniq = {};
var arrFiltered = data.filter(obj => !uniq[obj.project] && (uniq[obj.project] = true));
console.log(arrFiltered);

Related

How to convert array to object using loop (forEach, map, etc..) in Javascript

From
[
{
"id": "0001",
"name": "Jack",
"completeName": "Jack Smith"
},
{
"id": "0002",
"name": "Mary",
"completeName": "Mary Jackson"
},
{
"id": "0003",
"name": "John",
"completeName": "John Doe"
}
]
to this:
{
"Jack" :{
"id": "0001",
"name": "Jack",
"completeName": "Jack Smith"
},
"Mary" : {
"id": "0002",
"name": "Mary",
"completeName": "Mary Jackson"
},
"John": {
"id": "0003",
"name": "John",
"completeName": "John Doe"
}
}
You can use .map() and Object.fromEntries().
var data = [{
"id": "0001",
"name": "Jack",
"completeName": "Jack Smith"
},
{
"id": "0002",
"name": "Mary",
"completeName": "Mary Jackson"
},
{
"id": "0003",
"name": "John",
"completeName": "John Doe"
}
];
var result = Object.fromEntries(data.map(el => [el.name, el]));
console.log(result);
1. using forEach :
var data = [{
"id": "0001",
"name": "Jack",
"completeName": "Jack Smith"
},
{
"id": "0002",
"name": "Mary",
"completeName": "Mary Jackson"
},
{
"id": "0003",
"name": "John",
"completeName": "John Doe"
}
];
var result = {};
data.forEach(function(val) {
result[val["name"]] = val;
});
console.log(result);
2. Using object.assign and map:
var data = [{
"id": "0001",
"name": "Jack",
"completeName": "Jack Smith"
},
{
"id": "0002",
"name": "Mary",
"completeName": "Mary Jackson"
},
{
"id": "0003",
"name": "John",
"completeName": "John Doe"
}
];
let dictionary = Object.assign({}, ...data.map((x) => ({
[x.name]: x
})));
console.log(dictionary);
You can use an array reduce method.
Array.prototype.reduce()
const test = [
{
"id": "0001",
"name": "Jack",
"completeName": "Jack Smith"
},
{
"id": "0002",
"name": "Mary",
"completeName": "Mary Jackson"
},
{
"id": "0003",
"name": "John",
"completeName": "John Doe"
}
];
const results = test.reduce((obj, props) => {
obj[props.name] = props;
return obj;
} , {});
console.log(results);
You need to take your data, let's say it's stored in the data variable, and reduce() it with this one-liner:
const output = data.reduce((acc, row) => ({ ...acc, [row.name]: row }), {} );
const data = [
{
id: '0001',
name: 'Jack',
completeName: 'Jack Smith',
},
{
id: '0002',
name: 'Mary',
completeName: 'Mary Jackson',
},
{
id: '0003',
name: 'John',
completeName: 'John Doe',
},
];
const output = data.reduce((acc, row) => ({ ...acc, [row.name]: row }), {});
console.log(output);

Replacing content of array on the basis of property

I am working on an angular application. I have two arrays as follows:
array1 = [
{
Name: "Jack",
Id: "1",
Location: "UK"
},
{
Name: "Rose",
Id: "2",
Location: "USA"
},
{
Name: "Mary",
Id: "3",
Location: "India"
}
];
array2 = [
{
Name: "Raj",
Id: "5",
Location: "UK"
},
{
Name: "John",
Id: "2",
Location: "Germany"
},
{
Name: "Maria",
Id: "3",
Location: "Canada"
}
];
I want a resultant array such that If "Id" of any element of array1 matches "Id" of any element in array2, then whole data for that particular "Id" should be replaced in array2. So my resulArray will look as follows:
resultArray = [
{
Name: "Raj",
Id: "5",
Location: "UK"
},
{
Name: "Rose",
Id: "2",
Location: "USA"
},
{
Name: "Mary",
Id: "3",
Location: "India"
}
];
So Id= 2 and Id =3 of array 1 matches in array2, so data of Id=2 and Id=3 in array2 are replaced by that of array1. How can I do it?
You need map and find here. You can put an OR condition that if value is present in array1 if so then will pick the object from array1 otherwise the current object will be chosen.
var array2=[ { "Name": "Raj", "Id": "5", "Location": "UK" }, { "Name": "John", "Id": "2", "Location": "Germany" }, { "Name": "Maria", "Id": "3", "Location": "Canada" }];
var array1= [{ "Name": "Jack", "Id": "1", "Location": "UK"},{ "Name": "Rose", "Id": "2", "Location": "USA"},{ "Name": "Mary", "Id": "3", "Location": "India"}];
var result = array2.map(p=>(array1.find(k=>k.Id==p.Id) || p));
console.log(result);
I hope this helps.
You can use reduce and find function for your requirement
array2.reduce((acc, c) => {
var existed = array1.find(a=>a.Id == c.Id);
if(existed){
c.Name = existed.Name;
}
return c;
}, [])
var array1= [
{
"Name": "Jack",
"Id": "1",
"Location": "UK"
},
{
"Name": "Rose",
"Id": "2",
"Location": "USA"
},
{
"Name": "Mary",
"Id": "3",
"Location": "India"
}
]
var array2=[
{
"Name": "Raj",
"Id": "5",
"Location": "UK"
},
{
"Name": "John",
"Id": "2",
"Location": "Germany"
},
{
"Name": "Maria",
"Id": "3",
"Location": "Canada"
}
];
array2.reduce((acc, c) => {
var existed = array1.find(a=>a.Id == c.Id);
if(existed){
c.Name = existed.Name;
}
return c;
}, [])
console.log(array2)

merge two arrays including some fields from each

I want to merge two arrays using map function, the idea is to create a new array with some fields taken from first array and some fields from the second one.
The condition is the field name.
Here is list A:
[
{"name": "tom", "id": "1", "date": "1654"},
{"name": "jack", "id": "2", "date": "6544"},
{"name": "sarah", "id": "3", "date": "987"},
{"name": "william", "id": "4", "date": "654"},
{"name": "ronaldo", "id": "5", "date": "12345"}
]
and here is list B:
[
{"name": "tom", "age": "20", "school": "A", "password": "abcd"},
{"name": "jack", "age": "25", "school": "B", "password": "1234"}
]
as a result, it should return a merged version, but only some selected fields included:
[
{"name": "tom", "age": "20", "school": "A", "exists": true, , "date": "1654"},
{"name": "jack", "age": "25", "school": "B", "exists": true, "date": "6544"},
{"name": "sarah", "age": "", "school": "", "exists": false, "date": "987"},
{"name": "william", "age": "", "school": "", "exists": false, "date": "654"},
{"name": "ronaldo", "age": "", "school": "", "exists": false, "date": "12345"}
]
Here is my attempt to merge these two arrays, using map, but not very successful. Could somebody help me to achieve this?
const alldata = listA.map(u => listB.filter(oo => u.name === oo.name));
I used name as the key to find whether an entry from a is present in b and created the required list with appropriate values from both the lists.
a = [
{"name": "tom", "id": "1", "date": "1654"},
{"name": "jack", "id": "2", "date": "6544"},
{"name": "sarah", "id": "3", "date": "987"},
{"name": "william", "id": "4", "date": "654"},
{"name": "ronaldo", "id": "5", "date": "12345"}
];
b=[
{"name": "tom", "age": "20", "school": "A", "password": "abcd"},
{"name": "jack", "age": "25", "school": "B", "password": "1234"}
];
c = a.map(a1 => {
let b3 = b.find(b1=>b1.name === a1.name) || {};
return {name: a1.name, age: b3.age || "", school: b3.school || "", exists: b3.name != undefined, date: a1.date}
})
console.log(c)
with this answer you're not creating new arrays.
let a = [{"name": "tom","id": "1","date": "1654"},{"name": "jack","id": "2","date": "6544"},{"name": "sarah","id": "3","date": "987"},{"name": "william","id": "4","date": "654"},{"name": "ronaldo","id": "5","date": "12345"}],
b = [{"name": "tom","age": "20","school": "A","password": "abcd"},{"name": "jack","age": "25","school": "B","password": "1234"}];
a.forEach((key, index)=>{
let exists;
b.forEach((bkey, bindex)=>{
if(key.name==bkey.name){
a[index] = {...a[index], ...b[bindex]};
exists = bkey.age;
}
});
a[index].exists = !!exists;
});
console.log(a);
You are very close. Try this:
let arrA = [
{"name": "tom", "id": "1", "date": "1654"},
{"name": "jack", "id": "2", "date": "6544"},
{"name": "sarah", "id": "3", "date": "987"},
{"name": "william", "id": "4", "date": "654"},
{"name": "ronaldo", "id": "5", "date": "12345"}
];
let arrB = [
{"name": "tom", "age": "20", "school": "A", "password": "abcd"},
{"name": "jack", "age": "25", "school": "B", "password": "1234"}
];
let result = arrA.map(v => {
let fr = arrB.filter(f => v.name == f.name ) ;
let e = fr.length ? true : false;
fr = fr.length ? fr[0] : {age: "", school: "", password: "" };
//Construct the format you want on the final array
return {
name: v.name,
age: fr.age,
school: fr.school,
exists: e,
date: v.date
}
});
console.log( result );
Use map to create new array and filter to find the matched element from the second element
var a = [{
"name": "tom",
"id": "1",
"date": "1654"
},
{
"name": "jack",
"id": "2",
"date": "6544"
},
{
"name": "sarah",
"id": "3",
"date": "987"
},
{
"name": "william",
"id": "4",
"date": "654"
},
{
"name": "ronaldo",
"id": "5",
"date": "12345"
}
]
var b = [{
"name": "tom",
"age": "20",
"school": "A",
"password": "abcd"
},
{
"name": "jack",
"age": "25",
"school": "B",
"password": "1234"
}
]
var c = a.map(function(item) {
let d = b.filter(function(items) {
return item.name === items.name;
})
if (d.length > 0) {
item.age = d[0].age;
item.school = d[0].school;
item.password = d[0].password
}
return item;
})
console.log(c)
const list1 = [
{"name": "tom", "id": "1", "date": "1654"},
{"name": "jack", "id": "2", "date": "6544"},
{"name": "sarah", "id": "3", "date": "987"},
{"name": "william", "id": "4", "date": "654"},
{"name": "ronaldo", "id": "5", "date": "12345"}
];
const list2 = [
{"name": "tom", "age": "20", "school": "A", "password": "abcd"},
{"name": "jack", "age": "25", "school": "B", "password": "1234"}
];
const merged = list1.map(item => {
const list2Match = list2.filter(i => i.name === item.name)[0];
const obj = list2Match ? {school: list2Match.school, age: list2Match.age, exists: true} : { school: '', age: '', exists: false};
return {school:obj.school, age: obj.age, exists: obj.exists, name: item.name, date: item.date };
});

Javascript JSON Dynamic Parent

I am working on an ionic 1 app, I do not know if there is a way but for example, here, is there a way I can dynamically assign a parent in this JSON object depending on the value of the Variable?
var contact = {
"Name": "John Doe",
"available": true,
Variable: [
{
"Location": "Home",
"Number": "33"
},
{
"Location": "Work",
"Number": "22"
}
]
};
Lets say Variable = "friends"
Then
var contact = {
"Name": "John Doe",
"available": true,
"Friends": [
{
"Location": "Home",
"Number": "33"
},
{
"Location": "Work",
"Number": "22"
}
]
};
You can use braces notation [] and put variable in it.
var contact = {
"Name": "John Doe",
"available": true,
};
contact[Variable] = [
{
"Location": "Home",
"Number": "33"
},
{
"Location": "Work",
"Number": "22"
}
]
If using ES6 you can use Computer Property Names [Variable]: {}
var Variable = 'Friends';
var contact = {
"Name": "John Doe",
"available": true,
[Variable]: [
{
"Location": "Home",
"Number": "33"
},
{
"Location": "Work",
"Number": "22"
}
]
};

Group by JSON array using jQuery

I have a set of JSON array and I want the result to be grouped by the "Id" column. I will not use underscore.js for this, as this can't be used in our project. The only option is to do it with jQuery. My source array and expected results are below.
var origObj = [{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" },
{ "Id": "5", "name": "zzz", "age": "59" }]
var output = [{"1": [{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" }],
"5": [{ "Id": "5", "name": "zzz", "age": "59" }]}]
You can use Array.prototype.reduce to get this done. Check this post for more details https://stackoverflow.com/a/22962158/909535 Extending on that this is what you would need
var data= [{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" },
{ "Id": "5", "name": "zzz", "age": "59" }];
console.log(data.reduce(function(result, current) {
result[current.Id] = result[current.Id] || [];
result[current.Id].push(current);
return result;
}, {}));
Try
var origObj = [{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" },
{ "Id": "5", "name": "zzz", "age": "59" }], output;
output = [origObj.reduce((a,c) => (a[c.Id]=(a[c.Id]||[]).concat(c),a) ,{})];
console.log(output);

Categories

Resources