比较数组并使用条件对数组列表进行排序

时间:2015-03-09 14:12:36

标签: javascript arrays sorting

    MyValue = [name:"myValue", apple:3, banana:2];

    ListValue = [
        {name:"value1", apple:1, banana:2]},
        {name:"value2", apple:3, banana:2]},
        {name:"value2", apple:5, banana:1]},
        {name:"value4", apple:3, banana:3]},
        {name:"value5", apple:3, banana:5]}
        ]

你能帮我找到一个解决方案,用这个条件对NewListValue进行排序:如果MyValue的每个果实小于或等于ListValue的每个数组的每个果实

我想得到这样的结果:

NewListValue = [
{name:"value1", apple:1, banana:2]},
{name:"value2", apple:0, banana:1]}
]

非常感谢你!

1 个答案:

答案 0 :(得分:1)



 MyValue = { "name": "myValue", "apple": 3, "banana": 2 };

    ListValue = [
        {name:"value1", apple:1, banana:2},
        {name:"value2", apple:3, banana:2},
        {name:"value2", apple:5, banana:1},
        {name:"value4", apple:3, banana:3},
        {name:"value5", apple:3, banana:5}
        ];
    
 
    var NewListValue = ListValue.filter(function(element){
       if (MyValue.apple >= element.apple &&  MyValue.banana >= element.banana )
         {
           return element;
         }
    
    });

document.body.innerHTML += JSON.stringify(NewListValue ); //demo code




我会在这里使用Array.prototype.filter。然而,for循环也会起作用。

此处纠正了很多语法错误。将您的MyValue数组转换为对象而不是带有键的数组(不起作用)。

修复了ListValue数组。