[{
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
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
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;
};
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?
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>
613 GDB gets version error when attempting to debug with the Presense SDK (IDE)
578 Understanding How to Configure Google API Key
620 Uncaught (inpromise) Error on Electron: An object could not be cloned
916 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2024 OneMinuteCode. All rights reserved.