Skip to content
Advertisement

JavaScript merge arrays from two different functions

Hey I want to merge those two arrays and use it as one array.

Assigning variables:

var worldData = [];
var europeData = [];
var allData = [];

Code to fetch data from Data Source 1:

fetch('https://disease.sh/v3/covid-19/all')
    .then((res) => res.json())
    .then((data_world) => getWorldData(data_world));

First function:

const getAllData = (data_world) => {
  worldData = [
    data_world.todayCases,
    data_world.todayRecovered,
    data_world.todayDeath
  ];
  
  return worldData;
};

Code to fetch data from Data Source 2:

fetch('https://disease.sh/v3/covid-19/continents/Europe?strict=true')
    .then((res) => res.json())
    .then((data_eu) => getEuropeData(data_eu));

Second function:

const getEuropeData = (data_eu) => {
  europeData = [
    data_eu.todayCases,
    data_eu.todayRecovered,
    data_eu.todayDeath
  ];
  
  return europeData;
};

Merging arrays (didn’t work):

allData = [...worldData, ...europeData]
allData = worldData.concat(europeData)

I can’t put arrays outside these functions because i’m fetching data from two different sources and I want to store all data inside one array.

Advertisement

Answer

Found the answer but forgot to post there.

My solution:

let arr = [];

fetch('https://disease.sh/v3/covid-19/all')
  .then((res) => res.json())
  .then((data) => {
    arr.push(
      Object.values(data)[2],
      Object.values(data)[6]
    );
    return arr;
  });
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement