Get the sum of all specified elements in an array of objects

后端 未结 5 1923
一个人的身影
一个人的身影 2021-01-28 12:17

I have an array of objects as folllows

[
    {\"width\":128.90663423245883,\"height\":160,\"X\":0,\"Y\":140},
    {\"width\":277.0938568683375,\"height\":263,\"X         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-28 13:08

    If you are looking for solution without knowing index of element but you want only to send object, then you will need to check all properties of current item with available items and you can do it like this:

    var items = [
    {"width":128.90663423245883,"height":160,"X":0,"Y":140},
    {"width":277.0938568683375,"height":263,"X":128.90663423245883,"Y":37},
    {"width":264.8267031014369,"height":261,"X":277.0938568683375,"Y":39},
    {"width":229.14003389179788,"height":60,"X":264.8267031014369,"Y":240},
    {"width":10.032771905968888,"height":177,"X":229.14003389179788,"Y":123}
    ];
    
    function getAllBefore(current) {
        var sum = 0;
    
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            if (current.width == item.width && current.height == item.height && current.X == item.X && current.Y == item.Y)
            {
                 return sum;
            }
    
            sum += item.width;
        }
    }
    
    getAllBefore(items[2]);
    

提交回复
热议问题