我有一个类似下面的JSON
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']}]
现在基于爱好数组长度,前三个最大数组长度对象必须推送到一个数组,其余对象必须推送到另一个数组
我所期待的就像
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']}]
答案 0 :(得分:3)
您可以按照兴趣爱好的长度进行排序,然后将前三名放入resultantArray1
,其余的放入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);