I have an array of objects that look like this:
[{year: "1920", count: 0}, {year: "1921", count: 2}, {year: "1925", count: 0}, {year: "1930", count: 21}, ....]
I want to, based on a starting year(ex. 1900) and an ending year(ex. 2000) fill up all years in between in the array with objects({year: -year-, count: 0}), so in the example above, the years between 1900 and 1920 would be added, and 1921-1925, and 1925-1930, and 1930-2000.
Has anyone had a similar problem and can help? Would be very much appreciated!
Edit: What I have tried so far is a simple for loop, checking in each iteration if the year is in the array .. But I feel like that is not a good and efficient way to solve it
-
1It would be better if you let us know what you have tried so far.Jejun– Jejun2021年03月03日 07:39:28 +00:00Commented Mar 3, 2021 at 7:39
-
I have tried a simple for loop, checking in each iteration if the year is in the array .. But I feel like that is not a good and efficient way to solve it .. (Updated the original question) @Jejunalp123– alp1232021年03月03日 07:40:46 +00:00Commented Mar 3, 2021 at 7:40
-
Add the code that you've tried and what you're having trouble with. Adding more specific example output will help as well.Andy Ray– Andy Ray2021年03月03日 07:43:30 +00:00Commented Mar 3, 2021 at 7:43
3 Answers 3
You can first create an object from current years array and generate the new array while checking if the year present in that object:
const presentYear = [{year: "1920", count: 0}, {year: "1921", count: 2}, {year: "1925", count: 0}, {year: "1930", count: 21}];
const presentYearObj = Object.fromEntries(presentYear.map(k=>[k.year, k]));
const allData = Array.from({length:101}, (_,i)=>presentYearObj[`${1900+i}`] || ({year:`${1900+i}`, count:0}));
console.log(allData);
Comments
let arrs =
[
{year: "1920", count: 0},
{year: "1921", count: 2},
{year: "1925", count: 0},
{year: "1930", count: 21}
]
let arr2 = arrs.map(it => {
return +it.year
})
console.log(arr2)
for (let i = 1900; i < 2000; i++) {
if (!arr2.includes(i)) {
arrs.push({year: i + '', count: 0})
}
}
console.log(arrs.length)
Comments
function fillYears(from, to, existingArray) {
let existingObject = {};
existingArray.map(x => existingObject[x.year] = x.count);
let yearsArray = [];
for (let i = from; i <= to; i++) {
yearsArray.push({
year: i.toString(),
count: existingObject[i] || 0
});
}
return yearsArray;
}
let arrYears = [
{ year: "1920", count: 0},
{ year: "1921", count: 5},
{ year: "1925", count: 0},
{ year: "1930", count: 10}
];
arrYears = fillYears(1900, 2000, arrYears);
console.log( arrYears );
This function creates a new array, completing the count values from the existing array.