1

I have a piece of code for removing duplicates from an array of object in ES6 as follows

function removeDuplicates(myArr, prop) {
    return myArr.filter((obj, pos, arr) => {
        return arr.map(mapObj => mapObj[prop]).indexOf(obj[prop]) === pos;
    });
}

I am trying to understand the map function here using ES5 standards. Is there any other way to better write the above code in ES5 format? Thanks in advance

krishna teja
  • 159
  • 2
  • 9
  • Just change the arrow functions, nothing else in your code is ES6+ – CertainPerformance Dec 06 '18 at 23:57
  • @CertainPerformance I am kind of confused with the syntax, like where the indexOf is getting operated on and what is getting returned etc. filter function is clear but I I have issue understanding map function here. – krishna teja Dec 07 '18 at 00:03
  • The `.indexOf` is being called on the previous expression. – CertainPerformance Dec 07 '18 at 00:04
  • 1
    `return arr.map(function(mapObj) { return mapObj[prop]; }).indexOf(obj[prop]) === pos;` – ibrahim mahrir Dec 07 '18 at 00:06
  • 1
    Or simpler `var props = arr.map(function(mapObj) { return mapObj[prop]; });` then `return props.indexOf(obj[prop]) === pos;` – ibrahim mahrir Dec 07 '18 at 00:07
  • BTW `removeDuplicates` can further be optimized by using `findIndex` instead of `map/indexOf` combo: – ibrahim mahrir Dec 07 '18 at 00:31
  • `function removeDuplicates(myArr, prop) {     return myArr.filter(function(obj, pos) {                         return myArr.findIndex(function(findObj) {                       return findObj[prop] === obj[prop];                      }) === pos;                                              });                                                      }                                                   ` – ibrahim mahrir Dec 07 '18 at 00:31

0 Answers0