1

I want to create the array below with a for loop as its large

var centres = {
    1979: { x: width * 1 / 41, y: height / 2 },
    1980: { x: width * 2 / 41, y: height / 2 },
    1981: { x: width * 3 / 41, y: height / 2 },
    ...
}

and then access it as follows:

function nodeYearPos(d) {
   return yearCenters[d.year].x;
}

I have the following code, but its only setting the year...

  var yearCenters = Array.from(new Array(2020-1919+1), (x, i) => i + 1919);
  for (year = 1919; year <= 2020; year++) {
    coords = getCentres(year); // this returns an object in the form {x : x, y : y}
    yearCenters[year] = coords;
  }
2
  • 1
    use an object, not an array. arrays are 0-indexed Commented Sep 20, 2020 at 18:33
  • yearCenters = Object.fromEntries(Array.from(new Array(2020-1919+1), (x, i) => [i + 1919,null])); convert the array to object and then set values. Commented Sep 20, 2020 at 18:39

2 Answers 2

1

you can do as gorak commented but with the getCenters function

var yearCenters = Object.fromEntries(Array.from(new Array(2020-1919+1), (x, i) => [i + 1919, getCenters(i + 1919)]));

or you can also try

var yearCenters = {};
for (year = 1919; year <= 2020; year++) {
  coords = getCenters(year);
  yearCenters[year] = coords;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I used the latter suggestion as this is nice and clear with its creation of an empty object ({}) and then populating it.
1

When you try to fetch by year in yearCenters array (e.g. yearCenters[year]) this won't work since the year is not the index in the array.

I would suggest you first convert the array into a JS object so that indexing on it works with years.

See below snippet -

// Create obejct from array
var yearCenters = Object.fromEntries(Array.from(new Array(2020-1919+1), (x, i) => [i + 1919, null]))
     
// This loop remains same
for (year = 1919; year <= 2020; year++) {
    coords = getCentres(year); // this returns an object in the form {x : x, y : y}
    yearCenters[year] = coords; 
}

// Mock function
function getCentres(year) {
  return {
    x: Math.random() * 100,
    y: Math.random() * 100
  }
}

console.log(yearCenters)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.