javascript [JS] Array Cardio 1

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript [JS] Array Cardio 1相关的知识,希望对你有一定的参考价值。

// Array.prototype.filter()
// 1. Filter the list of inventors for those who were born in the 1500's
const newArray = inventors.filter(inventor => {
  return inventor.year >= 1500 && inventor.year < 1600;
});

console.table(newArray);

// Array.prototype.map()
// 2. Give us an array of the inventors' first and last names
const nameArray = inventors.map(inventor => {
  return `${inventor.first} ${inventor.last}`;
});

console.table(nameArray);
// Array.prototype.sort()
// 3. Sort the inventors by birthdate, oldest to youngest
const birthArray = inventors.sort((a, b) => {
  return a.year > b.year ? 1 : -1;
});

console.table(birthArray);

// Array.prototype.reduce()
// 4. How many years did all the inventors live?
const totalYear = inventors.reduce((total, inventor) => {
  return total + (inventor.passed - inventor.year);
}, 0);

console.table(totalYear);
// 5. Sort the inventors by years lived
const ageSort = inventors.sort((a, b) => {
  return a.passed - a.year > b.passed - b.year ? 1 : -1;
});

console.table(ageSort);

// 8. Reduce Exercise
// Sum up the instances of each of these
const data = [
  "car",
  "car",
  "truck",
  "truck",
  "bike",
  "walk",
  "car",
  "van",
  "bike",
  "walk",
  "car",
  "van",
  "car",
  "truck"
];

const transportation = data.reduce((obj, item) => {
  if (!obj[item]) {
    obj[item] = 0;
  }
  obj[item]++;
  console.table(obj);
}, {});

console.table(obj);

以上是关于javascript [JS] Array Cardio 1的主要内容,如果未能解决你的问题,请参考以下文章

js 对象的循环

Javascript的精华

javascript array.length #array #js

javascript array flatten #js #array

javascript array flatten #js #array

javascript array flatten #js #array