skip to Main Content

I have an array of objects with duplicates:

[
  {
    "code": "d1",
    "title": "Title 1"
  },
  {
    "code": "d2",
    "title": "Title 2"
  },
  {
    "code": "d3",
    "title": "Title 3"
  },
  {
    "code": "d4",
    "title": "Title 4"
  },
  {
    "code": "d4",
    "title": "Title 4"
  },
  {
    "code": "d3",
    "title": "Title 3"
  }
]

So i want the output to be having only the once which doesn’t have duplicates included like below:

[
  {
    "code": "d1",
    "title": "Title 1"
  },
  {
    "code": "d2",
    "title": "Title 2"
  }
]

Any help would be appreciated, Thanks!

3

Answers


    • Find unique’s values in an array.
    const ressult = YourArray.filter(
      (value, index, array) => array.findIndex((v) => v.code === value.code) === index
    );
    
    Login or Signup to reply.
  1. Here is one way of doing it:

    const products=[
      {
    "code": "d1",
    "title": "Title 1"
      },
      {
    "code": "d2",
    "title": "Title 2"
      },
      {
    "code": "d3",
    "title": "Title 3"
      },
      {
    "code": "d4",
    "title": "Title 4"
      },
      {
    "code": "d4",
    "title": "Title 4"
      },
      {
    "code": "d3",
    "title": "Title 3"
      }
    ];
    
    const res=Object.entries(products.reduce((a,c)=>{
       (a[c.code+"|"+c.title]??=[]).push(c);
       return a;
     },{})).reduce((a,[k,v])=>{
       if(v.length==1) a.push(v[0]);
       return a;
     },[]);
    
    console.log(res);

    My approach involves two .reduce() loops:

    • In the first one I generate an object that collects all elements of the original array behind a compound key made up of the properties of the elements.
    • the object is then converted into an array again with Object.entries()
    • and in a second .reduce() only those elements will be collected (i. e.: their first element) into the target array that have a length of 1
    Login or Signup to reply.
  2.         let val = [
              {
                "code": "d1",
                "title": "Title 1"
              },
              {
                "code": "d2",
                "title": "Title 2"
              },
              {
                "code": "d3",
                "title": "Title 3"
              },
              {
                "code": "d4",
                "title": "Title 4"
              },
              {
                "code": "d4",
                "title": "Title 4"
              },
              {
                "code": "d3",
                "title": "Title 3"
              }
            ];
            let distinctVal = getDistincts(val);
            function getDistincts(val){
              let obj={};
              for (let i = 0; i < val.length; i++) {
                obj[`${val[i]["code"]}`]=val[i]["title"];
              }
              return obj;
            }
            console.log(distinctVal);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search