0

I'm not looking for an answer for simple array, but I am facing a problem when I have nested level array of objects.

So far I have seen similar answers for simple arrays but not for a complex nested one.

Below is my duplicate array, it has sub-level of items and objects, and I want to match the file object name and find the duplicate based on that.

I tried to apply below function but, it does not work for me. Please tell me how to modify the below function to my array?

var myArr = [
  {file: {name: "sakthi1.jpg"}, checked: true}, 
  {file: {name: "sakthi2.jpg"}, checked: true}, 
  {file: {name: "sakthi2.jpg"}, checked: true}, 
  {file: {name: "sakthi2.jpg"}, checked: true}
];

function removeDuplicates(myArr, prop) {
  return myArr.filter((obj, pos, arr) => {
    return arr.map(mapObj => mapObj[prop]).indexOf(obj[prop]) === pos;
  });
}
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
User123
  • 453
  • 2
  • 6
  • 17

1 Answers1

1

I think you can make use of map in javascript. Iterate through the array, store the unique element (in your case name) in the map. And check if its present in the map, if present then remove the element from current index. Else put the 'name' in map.

let myArr = [{file: {name: "sakthi1.jpg"}, checked: true}, {file: {name: "sakthi2.jpg"}, checked: true}, {file: {name: "sakthi2.jpg"}, checked: true}, {file: {name: "sakthi2.jpg"}, checked: true}];
let mapOfUniqueElements = new Map();

    function removeDuplicates(myArr, prop) {
        $.each(myArr,function(k,v){
          let name  = v['file']['name'];
          if(mapOfUniqueElements.get(name)){
            //remove the element from array
          }else{
            mapOfUniqueElements.set(name, 'present');
          }
        })
    };
Ishwar Rimal
  • 1,071
  • 11
  • 19