ES6 - Array Helpers

ES6 - Array Helpers

ES6 array helpers

Helper - forEach

Documentation

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

images.forEach(
    function(image){
        areas.push(image.height*image.width)
    }
);

console.log('Areas =', areas);

Helper - map

Documentation

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

const speeds = trips.map(
    function(trip){
        return trip.distance/trip.time;
    }
)

console.log( speeds);

Helper - filter

Documentation

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

const filteredUsers = users.filter( function(user){
        return user.admin === true;
    });

console.log('Admin users:', filteredUsers);

Helper - find

Documentation

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

const admin = users.find( function(user){
    return user.admin;
});

console.log('Admin=', admin);

Helpers - every & some

Documentation:  some  every

const users = [
  { id: 21, hasSubmitted: true },
  { id: 62, hasSubmitted: false },
  { id: 4, hasSubmitted: true }
];

const hasSubmitted = users.every(function(user){return user.hasSubmitted});
console.log('All users submitted?', hasSubmitted);
const requests = [
  { url: '/photos', status: 'complete' },
  { url: '/albums', status: 'pending' },
  { url: '/users', status: 'failed' }
];

const inProgress = requests.some(
    function(req){
        return req.status === 'pending'
    });

console.log('Pending requests:', inProgress);

Helper - reduce

Documentation

const reduceSum = numbers.reduce( 
    function(acc, cur){ 
        return acc+cur
    },0);

console.log('Sum with reduce:', reduceSum);
function unique(array) {
    return array.reduce(
        function(acc,cur){
            if (!acc.find( el => el === cur )) { 
                acc.push(cur);
            };
            return acc;
        },[]);
};

console.log('Unique', unique([1, 1, 2, 3, 4, 4]));