-2

I am trying to duplicate value only one time as well as unique from my JSON array.

I have tried the following code.

return_data = {};
return_data.planner = [{
    "date": "2019-08-30T12:10:08.000Z",
    "event": [{
      "name": "Event 1",
      "color": "#ccccc"
    }]
  },
  {
    "date": "2019-09-30T10:10:08.000Z",
    "event": [{
        "name": "Event 5",
        "color": "#ccccc"
      },
      {
        "name": "Event 4",
        "color": "#ccccc"
      },
      {
        "name": "Event 3",
        "color": "#ccccc"
      }
    ]
  },
  {
    "date": "2019-09-30T10:10:08.000Z",
    "event": [{
        "name": "Event 5",
        "color": "#ccccc"
      },
      {
        "name": "Event 4",
        "color": "#ccccc"
      },
      {
        "name": "Event 3",
        "color": "#ccccc"
      }
    ]
  },
  {
    "date": "2019-09-30T10:10:08.000Z",
    "event": [{
        "name": "Event 5",
        "color": "#ccccc"
      },
      {
        "name": "Event 4",
        "color": "#ccccc"
      },
      {
        "name": "Event 3",
        "color": "#ccccc"
      }
    ]
  }
];
res.header('Content-Type', 'application/json');
res.send(JSON.stringify(return_data));

Using above json array:

var u_array = [];
var tem = JSON.parse(JSON.stringify(return_data.response.planner));
for (var i = 0; i < tem.length; i++) {
  console.log(tem[i].date);
  var status = true;
  for (var j = 0; j < u_array.length; j++) {
    if (u_array[j].date == tem[i].date) {
      status = false;
      break;
    }
  }
  if (status) {
    u_array.push(tem[i]);
  }
};

return_data.response.planner = u_array;

I expect the duplicate value only one time with unique values.

shrys
  • 5,860
  • 2
  • 21
  • 36

1 Answers1

0

There are many different ways to do what you need. You can follow this thread for some pointers.

Here's one way to get distinct-

/**
 * inputArray = Input array 
 * keySelector = A function to select which key should be used to determine if element is distinct
 * keepFirstMatch = 
 *  true - If there is a matching element, and you want to keep the first original item
 *  false - If there is a matching element and you want to override the original item so that it gets overwritten by latest value in the array
 */

function getDistinct(inputArray, keySelector, keepFirstMatch = false) {

  const result = inputArray.reduce((acc, curr) => {

    if (keepFirstMatch) {
      if (typeof (acc[keySelector(curr)]) === 'undefined') {
        acc[keySelector(curr)] = curr;
      }
    } else {
      acc[keySelector(curr)] = curr;
    }
    return acc;
  }, {});

  return Object.keys(result).map(k => result[k]);
}

let distinct = getDistinct(planner, (c) => c.date);
Pankaj
  • 538
  • 4
  • 13