1

In a reactJS app I have an array of hex values that is being reordered, apparently "on evaluation". When logged right after declaration the expanded values are listed in a different order to the unexpanded values. It's this expanded order that the app uses, but the unexpanded order (the declared order) that I expected.

Compare image to snippet, hopefully this is clear.

Btw, I know I can sort it and I know I can put the array directly in the component. I have already solved the problem by adding a key to the array. But I want to understand why it's happening.

const chartColours = [
  '#003f5c',
  '#f8b3df',
  '#c4d94e',
  '#8588b1',
  '#496387',
  '#2f4b7c',
  '#c2b0d9',
  '#665191',
  '#a05195',
  '#d45087',
  '#f95d6a',
  '#ff7c43',
  '#ffa600',
  '#fff18f',
  '#fcc76b',
  '#309975',
  '#de425b'
];
console.log(chartColours);

console log screengrab

taids
  • 29
  • 4
  • 3
    Arrays don't magically show a different order without some code modifying them. Nothing shown will reproduce the issue – charlietfl Feb 09 '22 at 13:10
  • 2
    the problem is not reproducible with your code snippet. – tromgy Feb 09 '22 at 13:10
  • But your image shows a tooltip which gives a hint to what might have happened. The array might have changed since first printed, so when you expand it at some later time it might look different. – tromgy Feb 09 '22 at 13:13
  • The array is not being reordered on evaluation. Console output does not necessarily show the array content at the time of the output; if you do `console.log(JchartColours.join(', '));` instead though it will. –  Feb 09 '22 at 13:13
  • Something (in the code you haven't shown) modifies that array. Don't do that in React, keep your data immutable. – Bergi Feb 09 '22 at 13:14
  • As for *why* the expanded log can show something different, see https://stackoverflow.com/questions/4057440/is-chrome-s-javascript-console-lazy-about-evaluating-objects – Bergi Feb 09 '22 at 13:15

0 Answers0