Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to remove duplicates from array that contains nested object
    primarykey
    data
    text
    <p>I have an array of nested object (I use this to populate my tree), something like below..</p> <pre><code>var obj1= { text: "TreeRoot", items: [ { text: "subgroup1" , items: [ { text: "subgroup2", items: [ { text: "subgroup3", items: [ { text: "subgroup4", items: [ { text: "subgroup5" }] }] }] }] }] }; var obj2 = { text: "TreeRoot", items: [ { text: "subgroup1" , items: [ { text: "subgroup2", items: [ { text: "subgroup3", items: [ { text: "subgroup4", items: [ { text: "subgroup5" }] }] }] }] }] }; var obj3= { text: "TreeRoot", items: [ { text: "subgroup1" , items: [ { text: "subgroup2" }] }] }] }; var finalArray=[]; finalArray.push(obj1); finalArray.push(obj2); finalArray.push(obj3); </code></pre> <p>Now I need to remove the duplicate objects from my final array using text(i.e I should remove obj2 from my array)...</p> <p>This is what I tried..</p> <pre><code>var arr = {}; for ( var i=0; i &lt; finalPath.length; i++ ) arr[finalArray[i]['text']] = finalArray[i]; finalArray= new Array(); for ( key in arr ) finalArray.push(arr[key]); </code></pre> <p>Can someone let me know the best possible way?</p> <p>Edit:</p> <p>I think the below solution works, but yet to test it completely...</p> <pre><code>var arr = {}; for ( var i=0; i &lt; finalArray.length; i++ ){ if(finalArray[i].items){ for(var j=0;j&lt;finalArray[i].items.length;j++){ arr[finalArray[i].items[j]['text']] = finalArray[i]; } }else{ arr[finalArray[i]['text']] = finalArray[i]; } } finalArray= new Array(); for ( key in arr ) finalArray.push(arr[key]) </code></pre> <p>Thanks, Barani</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload