Question: Hi, my JS function returns the new array with latest time objects and merging all pics and videos. I just need to make an output
Hi, my JS function returns the new array with latest "time" objects and merging all "pics" and "videos". I just need to make an output of an array in order that was originally given(personnelMateriaRel, videos, contactor, pics, distributionResult, sendTime)
var data = [
/*Object 1*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.095949110729155,
"longitude": 113.28544487112273,
"time": "2020-01-02 17:04:38",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 16:01:54"
},
/*Object 2*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.09594105827961,
"longitude": 113.28548480963536,
"time": "2020-01-02 17:34:27",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 17:08:49"
},
/*Object 3*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.09594105827961,
"longitude": 113.28548480963536,
"time": "2020-01-02 17:34:27",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 17:08:49"
}
]
function resolve(array) {
let map = {};
let keys = ["pics","videos","personnelMateriaRel"];
array.forEach(element => {
let id = element.contactor.id;
let eleTime = element.distributionResult.time;
let object = map[id]
if (!object) {
object = map[id] = {
contactor: element.contactor,
distributionResult: element.distributionResult,
sendTime: element.sendTime
}
} else {
let lastTime = object.distributionResult.time;
if (eleTime >= lastTime) {
object.contactor = element.contactor;
object.distributionResult = element.distributionResult;
object.distributionResult.time = eleTime;
object.sendTime = element.sendTime;
}
}
for (let value of keys) {
object[value] = object[value] ?
object[value].concat(element[value]) : [].concat(element[value])
}
});
return Object.keys(map).map(id => map[id])
}
console.log(resolve(data));
/*If you run the above code you will understand what i mean*/
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
