Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Map.
- // Allows us to loop an array to modify or add props in some way.
- // arr.map((value, index, array)) - map recieves a callback as an argument which is given each current
- // value, index and array of the iteration.
- const songs = [
- { id: 1, name: "best song", artist: "randoms" },
- { id: 2, name: "another song", artist: "dfgg" },
- { id: 3, name: "boring song", artist: "sdfs" },
- { id: 4, name: "best song", artist: "gdfg" },
- ];
- const map = songs.map((song, index, array) => {
- // Maps loop through arrays.
- const { artist, ...rest } = song;
- // console.log('Artist: ', artist);
- // console.log('Rest of properties: ', rest);
- return {
- ...rest,
- anotherProp: "adding to the new obj"
- };
- })
- //console.log(map);
- // Filter.
- // Works like a map, except the callback func needs to return either true or false.
- // If it returns true then the array keeps that element and if it returns false the element is filtered out.
- const array = [1,2,3,4,5];
- const onlyEvenNums = array.filter((value, index, array) => {
- // Filter will loop through each value in array and add to a new array in condition matches.
- return value % 2 === 0;
- })
- // console.log(onlyEvenNums);
- let strings = ["hello", "there", "you", "hero"];
- let filterStrings = strings.filter(string => {
- // Loop though each properties and if condition matches, add to new array.
- return string.includes("er");
- });
- // console.log(filterStrings);
- let filterArrayOfObjects = songs.filter(song => {
- return song.name === "best song";
- });
- // console.log(filterArrayOfObjects);
- // Reduce.
- // Reduce takes an array and reduces it into a single value. For example, with an array of numbers you can easily find the average of all values
- // the callback differs though to map and filter in the sense it now recieves the accumulator (i.e. it adds up all the return values).
- // array.reduce((acc, currValue, currindex, array))
- let nums = [1,2,3,4];
- var max = nums.reduce(function(a, b) {
- return Math.max(a, b);
- });
- // Iterate through array and add each properties (currentValue) to the accumulator of previous value.
- const sum = nums.reduce((accumulator, currentValue, currentIndex, array) => {
- return accumulator + currentValue;
- });
- //console.log(sum);
- let obj = songs.reduce((accumulator, currentValue) => {
- const { artist } = currentValue;
- // Accumulator
- accumulator[artist] = artist;
- return {...accumulator};
- }, {});
- console.log(obj);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement