I want to get duplicate JSON values in JavaScript.

Asked 2 years ago, Updated 2 years ago, 109 views

[{
    id: 1,
    name —hoge,
}, {
    id: 2,
    name —hoge,
}, {
    id : 3,
    name —Huga,
}, {
    id: 4,
    name —piyo,
}, {
    id —5,
    name —Huga,
}, {
    id: 6,
    name —hoge,
}]

name
from the above data in JavaScript I'd like to find a duplicate and get the following values, but I can't think of a way to do it.

//ideal
{
    hoge: [1,2,6],
    huga: [3,5]
}

// There is no problem with this.
[1, 2, 6, 3, 5]

What kind of programs would you put together?
Please let me use it as a reference.

Thank you for your cooperation.

javascript json

2022-09-30 18:02

4 Answers

vartemp={};
varans={};
array.forEach(function(obj){
    varbox=temp[obj.name]||(temp[obj.name]=[]);
    if(box.push(obj.id)==2){
        an [obj.name] = box;
    }
});

How about this


2022-09-30 18:02

I feel like my school assignments are being presented as they are...

b=function(array){
   var result={};
   for (vari=0;i<array.length;++i){
       varl=result [array[i].name];
       if(l===undefined){
           result [array[i].name] = [array[i].id]; 
       } else{
           l.push(array[i].id);
       }
    }
    // Remove something with length = 1
    var keys = [ ];
    for (vark in result) {
        keys.push(k);
    }
    for (vari=0;i<keys.length;++i){
        if(result[keys[i]].length<=1){
            delete result [keys[i]];
        } 
    }
    return result;
};


2022-09-30 18:02

 vararr=[{
    id: 1,
    name: "hoge",
}, {
    id: 2,
    name: "hoge",
}, {
    id : 3,
    name: "huga",
}, {
    id: 4,
    name: "piyo",
}, {
    id —5,
    name: "huga",
}, {
    id: 6,
    name: "hoge",
}];


(function(arr){
  varm = {};
  err.forEach(function(i){
      m[i.name]?m[i.name].push(i.id): m[i.name]=[i.id];
  });
  for (vari in m) {
    if(m.hasOwnProperty(i)&m[i].length==1) delete m[i];
  }
  console.log (JSON.stringify(m))
})(arr);

Is it like this?


2022-09-30 18:02

I feel like I can write intuitively with Underscore.js.

In groupBy, group by name.
Pick out two or more items.
Shape results with mapObject.
I am doing it like this

 vara=[{
    id: 1,
    name: 'hoge',
}, {
    id: 2,
    name: 'hoge',
}, {
    id : 3,
    name: 'huga',
}, {
    id: 4,
    name: 'piyo',
}, {
    id —5,
    name: 'huga',
}, {
    id: 6,
    name: 'hoge',
}];


var result=_.chain(a)
  .groupBy(function(o){return o.name;})
  .pick(function(o){returno.length>1;})
  .mapObject(function(o){return_.pluck(o, 'id');})
  .value();

document.querySelector('.result') .innerHTML = JSON.stringify(result);
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"></script>
<p class="result"></p> 


2022-09-30 18:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.