根據這篇 https://dev.to/duomly/13-useful-javascript-array-tips-and-tricks-you-should-know-2jfo
所做記錄
var fruits = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];
var uniqueFruits =Array.from(new Set(fruits));
console.log(uniqueFruits);
var uniqueFruits2 = [...new Set(fruits)];
var friends = [
{ name: 'John', age: 22 },
{ name: 'Peter'’, age: 23 },
{ name: 'Mark', age: 24 },
{ name: 'Maria', age: 22 },
{ name: '‘Monica', age: 21 },
{ name: 'Martha', age: 19 },
]
var NewFriends = Array.from(friends, ({name})=> name)
console.log(NewFriends);
// returns [“John”, “Peter”, “Mark”, “Maria”, “Monica”, “Martha”]
var fruits = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];
fruits.length = 0;
console.log(fruits); // returns []
var fruits = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];
var obj ={...fruits};
console.log(obj);
var newArray = new Array(10).fill('1');
console.log(newArray);
return ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]
var fruits = ['apple', 'banana', 'orange'];
var meat = ['poultry', 'beef', 'fish'];
var vegetables = ['potato', 'tomato', 'cucumber'];
var food = [...fruits, ...meat, ...vegetables];
console.log(food);
// [“apple”, “banana”, “orange”, “poultry”, “beef”, “fish”, “potato”, “tomato”, “cucumber”]
使用 filter() 和 includes() 方法
var numOne = [0, 2, 4, 6, 8, 8];
var numTwo = [1, 2, 3, 4, 5, 6];
var newSet = [...new Set(numOne)].filter(item => numTwo.includes(item));
console.log(newSet);
var colors = ['blue', 'white', 'green', 'navy', 'pink', 'purple', 'orange', 'yellow', 'black', 'brown'];
var randomColor = colors[(Math.floor(Math.random() * (colors.length)))];
console.log(randomColor);
var nums = [1, 5, 2, 6];
var sum = nums.reduce((x, y) => x + y);
console.log(sum); // returns 14