logo
down
shadow

Can we map over two arrays at same time in js?


Can we map over two arrays at same time in js?

By : Vaibhav Sharma
Date : November 21 2020, 04:01 AM
I hope this helps you . Assuming, the projectText and imageUrl contain the elements in order and have the same number of elements, you can simply access the url from imageUrl array using the index from projectText
code :
   <div ClassName="container">
        {projectText.map((project, index) => (
                <div key={index} className="project">
                <h3>{project}</h3>
                <img key={index} src={`../img/${imageUrl[index]}.png`} alt={project}/>
                <a role="button" className="btn" href={`https://${project}`} target="_blank" rel="noopener noreferrer">Github</a>
                </div>
              </div>
            ))}
            {/* experiment train */}


Share : facebook icon twitter icon
Getting time difference between two arrays containing multiple time values

Getting time difference between two arrays containing multiple time values


By : pinebanana
Date : March 29 2020, 07:55 AM
will be helpful for those in need You're accessing the same elements of the array each time through the loop, and you're overwriting $result rather than accumulating the differences. Try:
code :
$result = 0;
for ($x=0; $x<count($Tim1); $x++) {
    $result += (strtotime($Tim1[$x]->log_time) - strtotime($Tim2[$x]->log_time));
}
Sensor time distributions from arrays and cell arrays

Sensor time distributions from arrays and cell arrays


By : user2503526
Date : March 29 2020, 07:55 AM
wish of those help If I have understood the problem well enough for solving, it seems you don't need to worry about C for the output. Here's the code -
code :
num_sensors = size(A,2)%// No. of sensors

A = A'; %//' The tracking goes row-wise, so transpose the input array
A(A==-1)=nan; %//set minus 1's to NaNs as excluding elements
out = cell(num_sensors,1);  %// storage for ouput
for k1 = 1:num_sensors

    %// Per sensor subtractions
    per_sensor_subt = bsxfun(@minus,A,A(k1,:)); 

    %// Set all elements of its own row to NaNs to exclude own subtractions
    per_sensor_subt(k1,:)=nan; 

    %// Get all the non-nans that correspond to the valid output
    out{k1} = per_sensor_subt(~isnan(per_sensor_subt));
end
>> celldisp(out)
out{1} =
    10
    50
out{2} =
   -10
   -20
    10
    40
out{3} =
    20
   -10
    30
out{4} =
   -40
   -30
   -50
num_sensors = size(A,2)%// No. of sensors
A(A==-1)=nan; %//set minus 1's to NaNs as excluding elements
out = cell(num_sensors,1);  %// storage for ouput
for k1 = 1:num_sensors

    %// Per sensor subtractions
    per_sensor_subt = bsxfun(@minus,A,A(:,k1)); 

    %// Set all elements of its own row to NaNs to exclude own subtractions
    per_sensor_subt(:,k1)=nan; 

    %// Get all the non-nans that correspond to the valid output
    out{k1} = per_sensor_subt(~isnan(per_sensor_subt));
end
[m,n] = size(A)%// No. of sensors and measurements
A(A==-1)=nan; %//set minus 1's to NaNs as excluding elements

%// Per sensor subtractions
per_sensor_subt = bsxfun(@minus,A,permute(A,[1 3 2]))

%// Set all elements of its own row to NaNs to exclude own subtractions
own_idx = bsxfun(@plus,bsxfun(@plus,[1:m]',[0:n-1]*numel(A)),[0:n-1]*m);%//'
per_sensor_subt(own_idx)=nan;

%// Linear and row-col-dim3 indices of valid subtractions
idx = find(~isnan(per_sensor_subt))
[x,y,z] = ind2sub(size(per_sensor_subt),idx)

%// Get per sensor output
out = arrayfun(@(n) per_sensor_subt(idx(z==n)),1:n,'un',0)
%// Sort A row-wise
[sortedA,sorted_idx] = sort(A,2)

%// Set all invalid indices to zeros, so that later on we can use `nonzeros`
%// to extract out the valid indices
valid_sorted_idx = sorted_idx.*(sortedA~=-1)

%// Convert to a cell array
valid_sorted_idx_cell = mat2cell(valid_sorted_idx,ones(1,size(A,1)),size(A,2))

%// Extract the valid ones(nonzero indices) for the final output, C
C = cellfun(@(x) nonzeros(x), valid_sorted_idx_cell,'un',0)
Sorting 2 arrays using 2 threads takes more time than sorting the 2 arrays one by one

Sorting 2 arrays using 2 threads takes more time than sorting the 2 arrays one by one


By : binf
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Diagnosis
The reason you get practically the same time — and slightly more time from the threaded code than from the sequential code — is that clock() measures CPU time, and the two ways of sorting take almost the same amount of CPU time because they're doing the same job (and the threading number is probably slightly bigger because of the time to setup and tear down threads).
code :
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <pthread.h>
#include "timer.h"

struct thread_data
{
    int count;
    unsigned int *arr;
};

struct thread_data thread_data_array[2];

static
void insertionSort(unsigned int arr[], int n)
{
    for (int i = 1; i < n; i++)
    {
        unsigned int key = arr[i];
        int j = i - 1;

        while (j >= 0 && arr[j] > key)
        {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}

static
void *sortAndMergeArrays(void *threadarg)
{
    int count;
    unsigned int *arr;
    struct thread_data *my_data;

    my_data = (struct thread_data *)threadarg;
    count = my_data->count;
    arr =  my_data->arr;

    insertionSort(arr, count);

    pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
    int count = 10000;
    int i, rc;
    clock_t start, end, total_t;
    pthread_t threads[2];

    // get the loop count. If loop count is not provided take 10000 as default loop count.
    if (argc == 2)
        count = atoi(argv[1]);

    unsigned int arr1[count], arr2[count], copyArr1[count], copyArr2[count];

    srand(time(0));

    for (i = 0; i < count; i++)
    {
        arr1[i] = rand();
        arr2[i] = rand();

        copyArr1[i] = arr1[i];
        copyArr2[i] = arr2[i];
    }

    Clock clk;
    clk_init(&clk);

    start = clock();
    clk_start(&clk);
    for (int t = 0; t < 2; t++)
    {
        thread_data_array[t].count = count;
        if (t == 0)
            thread_data_array[t].arr = arr1;
        else
            thread_data_array[t].arr = arr2;

        rc = pthread_create(&threads[t], NULL, sortAndMergeArrays, (void *)&thread_data_array[t]);
        if (rc)
        {
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
    }

    pthread_join(threads[0], NULL);
    pthread_join(threads[1], NULL);
    clk_stop(&clk);
    end = clock();

    char buffer[32];
    printf("Elapsed using threads:  %s s\n", clk_elapsed_us(&clk, buffer, sizeof(buffer)));

    total_t = (double)(end - start);
    printf("CPU time using threads: %ld\n", total_t);

    start = clock();
    clk_start(&clk);
    insertionSort(copyArr1, count);
    insertionSort(copyArr2, count);
    clk_stop(&clk);
    end = clock();

    printf("Elapsed sequentially:   %s s\n", clk_elapsed_us(&clk, buffer, sizeof(buffer)));
    total_t = (double)(end - start);
    printf("CPU time sequentially:  %ld\n", total_t);

    return 0;
}
$ inssortthread23 100000
Elapsed using threads:  1.060299 s
CPU time using threads: 2099441
Elapsed sequentially:   2.146059 s
CPU time sequentially:  2138465
$ inssortthread23 200000
Elapsed using threads:  4.332935 s
CPU time using threads: 8616953
Elapsed sequentially:   8.496348 s
CPU time sequentially:  8469327
$ inssortthread23 300000
Elapsed using threads:  9.984021 s
CPU time using threads: 19880539
Elapsed sequentially:   20.000900 s
CPU time sequentially:  19959341
$
$ inssortthread23 100000
Elapsed using threads:  1.051229 s
CPU time using threads: 2081847
Elapsed sequentially:   2.138538 s
CPU time sequentially:  2132083
$ inssortthread23 100000
Elapsed using threads:  1.053656 s
CPU time using threads: 2089886
Elapsed sequentially:   2.128908 s
CPU time sequentially:  2122983
$ inssortthread23 100000
Elapsed using threads:  1.058283 s
CPU time using threads: 2093644
Elapsed sequentially:   2.126402 s
CPU time sequentially:  2120625
$

$ inssortthread23 200000
Elapsed using threads:  4.259660 s
CPU time using threads: 8479978
Elapsed sequentially:   8.872929 s
CPU time sequentially:  8843207
$ inssortthread23 200000
Elapsed using threads:  4.463954 s
CPU time using threads: 8883267
Elapsed sequentially:   8.603401 s
CPU time sequentially:  8580240
$ inssortthread23 200000
Elapsed using threads:  4.227154 s
CPU time using threads: 8411582
Elapsed sequentially:   8.816412 s
CPU time sequentially:  8797965
$
Destructuring arrays of arrays and getting first element at the same time?

Destructuring arrays of arrays and getting first element at the same time?


By : anestan
Date : March 29 2020, 07:55 AM
around this issue I have a question about array destructuring. I have a data shaped like this :
code :
let [[a], [b]] = sample;
console.log(a, b); // "1" "4"
Arrays created in functions,compile time or run time?

Arrays created in functions,compile time or run time?


By : Eduardo Fontes de Fr
Date : March 29 2020, 07:55 AM
wish help you to fix your issue What you are using is called a variable length array. It is not part of the C++ standard but some compilers support it as an extension.
To make your code standard compliant, don't use it. Use std::vector instead.
code :
std::vector<int> someFunction(int number){

    std::vector<int> sampleArray(number);

    // No need for this. sampleArray elements are zero initialized.
    /*
    for(int i = 0; i < number; i++){
        sampleArray[i] = 0;
    }
    */
    return sampleArray;
}
Related Posts Related Posts :
  • Add new property to object collection based on condition with lodash
  • Transforming an object with a javascript class
  • Why does the hash compare outputs true even without the salt parameter?
  • Moment.js comparison always returns false
  • Store polygon type of data on the `SQLite` database
  • Matching data depending on chosen preferences
  • issue which is related to vuex store + cookies
  • Order By custom order in object inside property
  • How to display a preselected value in a dropdown without 'onchange'
  • Storing a javascript promise
  • Replacing text in nested divs
  • Strange behavior with select list options when adding and removing tasks using javascript
  • NodeJS Ajv module alway log message ' $ref: keywords ignored in schema at path "#" '
  • How to create TTL Index on long timestamp in MongoDB
  • Make background snowflake element unclickable
  • How to store data into variable.?
  • What is the difference between a redux middleware and a redux-observable epic?
  • How can I merge HTML attributes with component data in Vue?
  • How to repeat an html element n number of times using javascript
  • How to style html and body from the main Angular component?
  • Wait for Page Load Before CGI Script is Loaded?
  • How to call an mobx-state-tree action if a computed view changes?
  • Using Hosted Fonts with p5.js
  • Is it possible to open Microsoft Edge from a page rendered in Internet Explorer via just HTML/JavaScript?
  • NodeError: write after end in NodeJS
  • Object Localization - Google Vision API
  • How can I check that a class constructor is called with proper attributes in Sinon?
  • AssertionError [ERR_ASSERTION]: Task function must be specified Error in Gulp
  • Bootstrap's .dropdown('toggle') works a bit too well: dropdown is then unusable
  • Trying to write a JS script that shows and changes certain object properties
  • Element requires two clicks to run function
  • All elements with class name has html inside JS
  • Why does this Javascript work in the browser console but not in Selenium's JavascriptExecutor?
  • HtmlUnit getting string with wrong encoding
  • Datatables can't use sort by column or search in content
  • How do you extend the timeout of a liberty webserver application so it will wait longer than 60 seconds?
  • Angular - Get router url before loading router
  • Table rowspan with ngFor Angular6
  • Ray Tracing a scene with triangle meshes with webgl 2.0, deferred shading, framebuffers
  • Scroll between sections when progress finished
  • KnockoutJS foreach deosn't iterate through collection
  • How to ensure orderly processing result of a websocket's callbacks?
  • javascript array into key value space separated string
  • an if statement returns true, but the condition won't trigger
  • ADF how to trigger a clientListener from the bean?
  • Vue-test-utils can't find `Set()`: ReferenceError: Can't find variable: Set
  • Pass datepicker's date parameter to get resources in FullCalendar
  • Model aggregating in viewer - coordinate issue
  • Send post data like curl
  • sorting array with decimal value in specific order using javascript
  • Javascript - object.offsetTop and .offsetLeft gives 0
  • Remove content of p tag
  • Line 28: Expected an assignment or function call and instead saw an expression
  • How to trigger hover programmatically in chartjs
  • How to create a function to avoid repetitive steps?
  • Parameter the property used to filter an array
  • Return array with fast-csv in Node
  • If statement with parenthesis in javascript
  • Connecting the Javascript CSS to the CSS
  • Empty table cells
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org