0

I am trying to resolve two arrays of length n into n objects with the same number of key value pairs as there are arrays. Each object should have a dynamic name key that correlates to the object's position.

For example, if there are 10 items in each array, there should be 10 objects and each objects should have a name key the is sequential --> Day[n]

The input will look like this:

// input
const temperatures: [65, 33]
const rain: [3, 8]

The output shape should look something like this:

// output
[
  {
    name: 'Day1',
    temperature: 65,
    rain: 3
  },
  {
    name: 'Day2',
    temperature: 33,
    rain: 8
  },
]

I've tried mapping through each array and creating an object for each array item and then combining them into one array of objects, but for some reasson, the results array only includes one set of the array names.

This is my code so far:

const temperature = [65, 33];
const rain = [3, 8];
const days = { name: 'Day1' };

const data1 = temperature.map((val) => {
  return { temperature: val };
});

const data2 = rain.map((val) => {
  return { rain: val };
});

const total = { ...days, ...data1, ...data2 };

console.log(total);

// output: { '0': { temperature: 65 }, '1': { temperature: 33 }, name: 'Day1' }

NOTE: I am creating the input arrays, so if there is any data I need to add or make changes to, that is a possibility.

5 Answers 5

1
const temperature = [65, 33];
const rain = [3, 8]; 
const length = Math.max(temperature.length, rain.length);

const output = [];

for(let i = 0; i < length; i++) {
  output.push({rain:rain[i], temperature:temperature[i], name:`Day${i+1}`});
}
Sign up to request clarification or add additional context in comments.

1 Comment

to be completely fair I noticed after that I didn't have the name property so I borrowed from the other answers
0

const 
  temperatures = [ 65, 33 ]
, rain         = [  3,  8 ]
, output = temperatures.map((t,i) =>
     ( { name        : `day${i+1}`
       , temperature : t
       , rain        : rain[i] 
     }))
;
console.log( output )
.as-console-wrapper {max-height: 100%!important;top:0;}

Comments

0

Assuming the input arrays are of the same size, one possible way of doing this would be the following:

const result = temperature.map((temp, index) => {
    return { name: `Day${index+1}`, temperature: temp, rain: rain[index] };
};

Although personally I don't think this is the cleanest or clearest way, and it may be worth considering changing the input types.

Comments

0

Your use case does not require the use of the map() function.

I assume that, both the arrays temperature and rain always have the same number of elements. That is, if temperature array has temperature data for 3 Days then, even the rain array should have rain data for 3 Days

By taking the above assumption, We can loop over the elements of temperature array and insert a single object for each day into a new and final array which is your expected output.

We will use the every() function to achieve out goal:

var finalArray = [];

temperature.every((element, index) => {
    finalArray.push({
        name: `Day ${index}`, //Use index+1 for Day 1 and not Day 0
        temperature: element,
        rain: rain[index]
    });
});

console.log(finalArray); //The output

4 Comments

Correct, both arrays will always have the same number of items. Would this solution work, if the input arrays included another array such as `const snow = [5, 10]?
Yes Of course! You can add snow: snow[index] after the rain key in the above snippet.
It will work in all cases. The limitation of this method is all arrays should have the same number of elements. If there is no rain in a particular day, you can set rain as 0 in the array to maintain the same count of elements. Similarly it applies for snow, temperature, etc.
I'm not worried differentiating array lengths. My main concern is the re-usability.
0

Create a function which accepts temperature and rain as parameter and returns the final result. Here we assume that both temperature and rain array are of same length.

const temperature = [65, 33];
const rain = [3, 8];

function convertArray(temperature, rain) {
    const result = [];
    for (let i = 0; i < rain.length; i++) {
        const weather = {
            name: `Day${i + 1}`,
            temperature: temperature[i],
            rain: rain[i]
        }
        result.push(weather)
    }
    return result;
}

console.log(convertArray(temperature, rain));

2 Comments

I like this approach. I assume that if I were to call the convertArray function with say, two or three different array such as snow, sleet or sunshine, this would work as well. My main goal is to make this function as reusable as possoible to accept any number of arrays with n length.
@TylerMorales, That's correct, i always prefer function to make code reusable. please upvote the answer..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.