logo
down
shadow

Sum multiple objects in multiple arrays and then average sums


Sum multiple objects in multiple arrays and then average sums

Content Index :

Sum multiple objects in multiple arrays and then average sums
Tag : javascript , By : BooTeK
Date : November 28 2020, 11:01 PM

around this issue I have a object with the name, race number` (1,2,3) and finishing position of multiple drivers. I want to iterate through each array and display (console.log is fine) the race number, finishing position and then average finishing position for each driver. , I just loop it and to get the race no use Object.keys()
 var data = {
        "drivers":[
        {
            "Name":"Smith",
                "races": [
                {
                    "race 1":"12"
                },
                {
                    "race 2":"6"
                },
                {
                    "race 3":"10"
                }
            ]
        },
        {
            "Name":"Jones",
                "races": [
                {
                    "race 1":"11"
                },
                {
                    "race 2":"6"
                },
                {
                    "race 3":"5"
                }
                ]
            }
        ]
    };


    for(var x in data.drivers) {
        console.log(data.drivers[x].Name + ":");
        var total = 0;
        for(var i in data.drivers[x].races) {
            var key = Object.keys(data.drivers[x].races[i]);
            total += parseInt(data.drivers[x].races[i][key]);
            console.log(key+ " finishing: "+data.drivers[x].races[i][key]);
        }
        console.log('Average finishing position: ' + (total/3).toFixed(1));
    }

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

MySQL return multiple rows with multiple joins and multiple sums


Tag : mysql , By : pjkinney
Date : March 29 2020, 07:55 AM
I hope this helps you . I am not entirely sure what you're going for, but here's a basic problem: you don't have a GROUP BY statement. When you use a grouping function like SUM, it tells mysql that you want to group results together. If you leave out GROUP BY, it groups everything into one row. If you want to have one row per user (I assume so, because you're selecting their names), you should say
GROUP BY users.id

Ajax post returns multiple arrays with objects that have multiple values


Tag : javascript , By : SA.
Date : March 29 2020, 07:55 AM
Hope this helps So I have a php file that gets messages from a database (ajax.php) and a javascript file that makes ajax request to that ajax.php file (main.js). , Your ajax.php should be like this
<?php


  foreach ($messages as $message) {
    $from = $message['contact_value'];
    $text = $message['message'];
    $date = $message['date'];
    $num = $user['phone_number'];
    echo json_encode(array("from"=>$from, "text"=>$text,"date"=>$date,"num"=>$num));
?>
 success: function (response) {
  var success = $.parseJSON(response);
  $(".messages-table").append("<tr><th>"+success.from+"</th><th>"+success.text+"</th><th>"+success.date+"</th><th>"+success.num+"</th></tr>");
}

How to merge multiple arrays and interpolate the sums of values if keys don't match?


Tag : php , By : SA.
Date : March 29 2020, 07:55 AM
With these it helps You could create a helper function that takes one key/value array and an array of keys, which returns a key/value array that will contain all the keys in the second array, and interpolated values where needed. The array of keys should have all the keys that exist in the first array, but can have more (not less):
function interpolate($a, $keys) {
    foreach($keys as $key) {
        if (key($a) === $key) {
            $prevValue = $result[$key] = current($a);
            $prevKey = $key;
            next($a);
        } else if (empty($prevKey)) {
            $result[$key] = 0;
        } else {
            $result[$key] = current($a) === false ? $prevValue 
                : $prevValue + (current($a) - $prevValue) 
                             * (strtotime($key) - strtotime($prevKey)) 
                             / (strtotime(key($a)) - strtotime($prevKey));
        }
    }
    return $result;
}
$keys = array_keys(array_merge($a1, $a2));
sort($keys);

$b1 = interpolate($a1, $keys);
$b2 = interpolate($a2, $keys);
foreach($b1 as $key => $value) {
    $sum[$key] = $value + $b2[$key];
}
$keys = array_keys(array_merge(...$a));
sort($keys);
$b = array_map(function ($a1) use ($keys) {
    return interpolate($a1, $keys);
}, $a);

foreach($keys as $key) {
    $sum[$key] = array_sum(array_column($b, $key));
}

Count value arrays in multiple columns and return per row sums


Tag : if-statement , By : user187383
Date : March 29 2020, 07:55 AM
will help you I'm trying to tally 7 columns and return the result for each row. But every variation of the formula I've tried has given the wrong result. Usually, it just tallies the entire range and returns the same result for every row.
=ARRAYFORMULA(IF(LEN(A3:A), 
 MMULT(IFERROR(LEN(B3:H)/LEN(B3:H), 0), TRANSPOSE(COLUMN(B2:H2)^0)), ))

U-sql : How to process an Avro file with multiple JSON arrays with multiple objects?


Tag : development , By : Techspirit
Date : March 29 2020, 07:55 AM
hope this fix your issue I got this to work by exploding the JSON column again and applying the JsonTuple function again (however I suspect it could be simplified):
@jsonify =
    SELECT JsonFunctions.JsonTuple(Encoding.UTF8.GetString(Body)) AS message
    FROM @rs;

// Explode the tuple as key-value pair;
@working =
    SELECT key,
           JsonFunctions.JsonTuple(value) AS value
    FROM @jsonify
         CROSS APPLY
             EXPLODE(message) AS y(key, value);
REFERENCE ASSEMBLY Avro;
REFERENCE ASSEMBLY [Newtonsoft.Json];
REFERENCE ASSEMBLY [Microsoft.Analytics.Samples.Formats]; 

USING Microsoft.Analytics.Samples.Formats.Json;

DECLARE @input_file string = @"\input\input21.avro";
DECLARE @output_file string = @"\output\output.csv";


@rs =
EXTRACT
 Body byte[]
FROM @input_file
USING new Microsoft.Analytics.Samples.Formats.ApacheAvro.AvroExtractor(@"{
    ""type"": ""record"",
    ""name"": ""EventData"",
    ""namespace"": ""Microsoft.ServiceBus.Messaging"",
    ""fields"": [
        {
            ""name"": ""SequenceNumber"",
            ""type"": ""long""
        },
        {
            ""name"": ""Offset"",
            ""type"": ""string""
        },
        {
            ""name"": ""EnqueuedTimeUtc"",
            ""type"": ""string""
        },
        {
            ""name"": ""SystemProperties"",
            ""type"": {
                ""type"": ""map"",
                ""values"": [
                    ""long"",
                    ""double"",
                    ""string"",
                    ""bytes""
                ]
            }
        },
        {
            ""name"": ""Properties"",
            ""type"": {
                ""type"": ""map"",
                ""values"": [
                    ""long"",
                    ""double"",
                    ""string"",
                    ""bytes"",
                    ""null""
                ]
            }
        },
        {
            ""name"": ""Body"",
            ""type"": [
                ""null"",
                ""bytes""
            ]
        }
    ]
}");


@jsonify =
    SELECT JsonFunctions.JsonTuple(Encoding.UTF8.GetString(Body)) AS message
    FROM @rs;

// Explode the tuple as key-value pair;
@working =
    SELECT key,
           JsonFunctions.JsonTuple(value) AS value
    FROM @jsonify
         CROSS APPLY
             EXPLODE(message) AS y(key, value);


@cnt =
    SELECT value["id"] AS id,
           value["id2"] AS pid,
           value["value"] AS value,
           value["utctimestamp"] AS utctimestamp,
           value["extra"] AS extra
    FROM @working;


OUTPUT @cnt TO @output_file USING Outputters.Text(quoting: false);
Related Posts Related QUESTIONS :
  • How to Make a jQuery Table Cell(td) clickable to Run a Function?
  • Prevent the duplicate function onchange event jQuery
  • Reactjs Input Upload doesn't return local URL
  • An unexpected 'StartObject' node was found when reading from the JSON reader. A 'PrimitiveValue' node was expected
  • How to filter a JSON Array, with an eventListener input value at keyup
  • How to separate the different properties of filter in css?
  • Why dont work change event of bootstrap input spinner?
  • How to hide overflow text content in react
  • Is there another way to write line 6
  • Cypress - how to find by text content?
  • How to setstate for the dynamic checkboxes in a loop in react?
  • Is display:none safe?
  • How to create a form to change part of a href url of a button?
  • Put many function inside function in Javascript
  • how to exit from loop after a ajax call
  • Do Angular Reactive Form Validator.min/max check Perform Type Conversions before checking the value?
  • How to Replace Text Within Script Tags Using JQuery
  • add variable to object if not undefined using short-hand
  • How can I effectively curve my items inside a list?
  • Add new record Keyboard Shortcut on Kendo Grid Mvc
  • Time and Date running on page
  • Looping through page links puppeteer doesn't return values from the newly loaded page
  • Problem with Navigator.geoLocation.getCurrentPosition not working
  • Trying to change the id of an element with Javascript
  • Embedded Schema Inserting Blank in Meteor using Collection2
  • avoid useEffect to render at first load?
  • Why is this CSS transition only working correctly on the some clicks? How to solve it?
  • Interpolated values does not reflect the latest values in an Angular app
  • Javascript classes define attribute in constructor or outside the class
  • How to block scroll event passing through to iframe until iframe is active?
  • What is the purpose of "constructor" method in javascript?
  • Stencil JS not working with non-default imports
  • Are frameworks misleadingly named for marketing purposes?
  • React <Redirect> after transition not working
  • How to send multiple parameters in a function using EJS
  • React conditional style on custom click
  • Push a block of information to an array X times based on an external variable
  • How do I populate dropdown with names, and values (numeric ids)?
  • How to apply styling to elements created with .insertAdjacentHtml method
  • Positioning key:value of an object
  • Referencing DOM Elements with React Hooks
  • TypeError: Method "getRange" of null when using multiple scripts (Libraries) in Google scripts
  • Why can't I check if an environment variable is undefined?
  • Is there a way to find what parts are the same between two strings?
  • Every change done with magicscroll and greensock get reset when I hit the bottom of the page
  • Fix a 'Cannot read property handleClick of undefined error' (and issues related to deleting an item from the DOM)
  • Answer to message if sent within a period of time
  • Enabling a button based on selected values
  • Get All possible matches between forward slashes
  • get the CSS maxWidth value of the parent javascript
  • Async function returning existing array as undefined
  • Using drop-down list to change multiple values in separate table cells
  • How to remove nested empty objects in JavaScript?
  • Convert value from text field to paragraph
  • Sorting a list based on instructions in Javascript
  • Post request doesn't work in NodeJS, OK with Request
  • How to make footer align to center in nested component scenario in React
  • fresh installed pwa does not show content
  • Working around unset "length" property on partial functions created with lodash's partialRight
  • V8 console.log does not print
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com