Midhunsai Midhunsai - 1 month ago 4
JSON Question

how to find the first three max length of array in JSON

i had a JSON like below

sampleArray=[{name:'john',hobbies:['sports','music']},
{name:'steve',hobbies:['singing','movies','playing']},
{name:'raj',hobbies:['movies']},
{name:'nikil',hobbies:['music','movies','playing','tennis']},
{name:'bose',hobbies:['sports','music']},
{name:'suku',hobbies:['music']},
{name:'sai',hobbies:['sports','music','watchingTv','movies','tennis']},
{name:'vivek',hobbies:['sports']},
{name:'ram',hobbies:['sports','music','watching']}]


now based on hobbies array length, first three maximum array lengths objects have to push to one array and remaining objects have to push to another array

what i am expecting is like

resultantArray1=[{name:'sai',hobbies:['sports','music','watchingTv','movies','tennis']},
{name:'nikil',hobbies:['music','movies','playing','tennis']},
{name:'steve',hobbies:['singing','movies','playing']}]



resultantArray2=[{name:'john',hobbies:['sports','music']},
{name:'raj',hobbies:['movies']},
{name:'bose',hobbies:['sports','music']},
{name:'suku',hobbies:['music']},
{name:'vivek',hobbies:['sports']},
{name:'ram',hobbies:['sports','music','watching']}]

Answer

You could sort by length of the hobbies and then just put the top 3 into the resultantArray1 and the rest to the resultantArray2

var sampleArray=[
                 {name:'john',hobbies:['sports','music']},
                 {name:'steve',hobbies:['singing','movies','playing']},
                 {name:'raj',hobbies:['movies']},
                 {name:'nikil',hobbies:['music','movies','playing','tennis']},
                 {name:'bose',hobbies:['sports','music']},
                 {name:'suku',hobbies:['music']},
                 {name:'sai',hobbies:['sports','music','watchingTv','movies','tennis']},
                 {name:'vivek',hobbies:['sports']},
                 {name:'ram',hobbies:['sports','music','watching']}
                ];

sampleArray.sort(function(a, b){
  return b.hobbies.length - a.hobbies.length;
});

var resultantArray1 = [].concat(sampleArray);
var resultantArray2 = resultantArray1.splice(3);

console.log(sampleArray);
console.log(resultantArray1);
console.log(resultantArray2);

Comments