简体   繁体   中英

Data showing in different order with console.log / console.table

--I'm doing this exercise with sort() and when I'm logging it in a console.table, it shows in the correct order and when I log it with console.log it shows in the wrong order.

--If I log a single item, arr[0] for example, it's the correct one that should display.

--How do I get around this behavior , I don't want to keep using console.table moving forward and I want to see correct data....

Console table <- printscreen with console table

Console log <- printscreen with console log and console log [0]

const inventors = [
  { first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
  { first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
  { first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
  { first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
  { first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
  { first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
  { first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
  { first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 },
  { first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 },
  { first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 },
  { first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 },
  { first: 'Hanna', last: 'Hammarström', year: 1829, passed: 1909 }
];

const outputThree = inventors.sort((a , b) => a.year - b.year )
console.table(outputThree)
console.log(outputThree)
console.log(outputThree[0])

It turns out I've done it to myself. I didn't realize that .sort() is mutating the original array and I was calling it for a different purpose later on in the code.

Thank you all for replying !

As you're doing it in the browser console - don't forget to refresh the page before each run.

Because if you don't - const outputThree... this will throw an error.

For me - Nicolaus Copernicus goes first in all examples with 1473 .

I tried with smaller data set and it seems to work correctly. Galileo goes first everywhere.

const inventors = [
  { first: 'Albert', year: 2 },
  { first: 'Isaac', year: 3 },
  { first: 'Galileo', year: 1 },
];

const outputThree = inventors.sort((a , b) => a.year - b.year )
console.table(outputThree) // Galileo first
console.log(outputThree) // Galileo first
console.log(outputThree[0]) // Galileo first

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM