フリーランス 技術調査ブログ

フリーランス/エンジニア Ruby Python Nodejs Vuejs React Dockerなどの調査技術調査の備忘録

ES6を利用する上でよく利用するメソッドの使用例①

利用するツール

これからのサンプルソースは下記のツールで実行すると実行結果がかえってきます。 https://stephengrider.github.io/JSPlaygrounds/ https://balsamiq.com/wireframes/cloud/

forEachメソッド

Case1

function handlePosts() {
    const posts = [
      { id: 23, title: 'JSニュース' },
      { id: 52, title: 'リファクター・シティ' },
      { id: 105, title: 'Rubyの良いところ' }
    ];
    
    posts.forEach(function(post){
      savePost(post);
    });
}

Case2

const images = [
  { height: 10, width: 30 },
  { height: 20, width: 90 },
    { height: 54, width: 32 }
];
let areas = [];

images.forEach(image => areas.push(image.height * image.width))
areas

>> [300,1800,1728]

mapメソッド

Case1

const images = [
  { height: '34px', width: '39px' },
  { height: '54px', width: '19px' },
  { height: '83px', width: '75px' },
];

let heights= []
heights = images.map(image => {return image.height})

>>["34px","54px","83px"]

Case2

const trips = [
  { distance: 34, time: 10 },
  { distance: 90, time: 50 },
  { distance: 59, time: 25 }
];

let speeds = [];
speeds = trips.map(trip => {return trip.distance / trip.time })

>> [3.4,1.8,2.36]

Case3

const colorObjects = [{ color: '赤' }, { color: '青' }, { color: '黄色' }];
let colorNames;
colorNames = colorObjects.map(colorObject => {return colorObject.color});

>> ["赤","青","黄色"]

filterメソッド

Case1

const numbers = [15, 25, 35, 45, 55, 65, 75, 85, 95];

let filteredNumbers;

filteredNumbers = numbers.filter(member => {return member >= 50})

>> [55,65,75,85,95]

Case2

const users = [
 { id: 1, admin: true },  
 { id: 2, admin: false },
 { id: 3, admin: false },
 { id: 4, admin: false },
 { id: 5, admin: true },
];

var filteredUsers;

filteredUsers = users.filter(user => {return user.admin})

>> [{"id":1,"admin":true},{"id":5,"admin":true}]

Case3(reject)

function reject(numbers,iteratorFunction){
  return numbers.filter(number => {return !iteratorFunction(number)})    
}

const numbers = [10, 20, 30];
const result = reject(numbers, function(number){
 return number > 25;
}); 
result

>> [10,20]

findメソッド

Case1

const users = [
  { id: 1, admin: false },
  { id: 2, admin: false },
  { id: 3, admin: true }
];

let admin;

admin = users.find(user => user.admin)

>> {"id":3,"admin":true}

Case2

const accounts = [
  { balance: -10 },
  { balance: 12 },
  { balance: 0 }
];

const account = accounts.find(account => account.balance == 12)
account

>> {"balance":12}

Case3

var ladders = [
    {id: 1, height: 20},
    {id: 3, height: 25},
]

function findWhere(objs,where){
  return objs.find(obj => {return obj.height == where.height})
}
const result = findWhere(ladders,{ height: 25 })
result

>> {"id":3,"height":25}