DevTUPLE

JS Hacks & Cheets #1

This blog is a handy cheat sheet for the JS developer community. This is part 1 of the complete blog. I tried to cover most of the use cases that are encountered in the day-to-day activities of a developer. If there is something I missed out on, contributions 🤝 are welcome🙌.

Simple Image to lighten you up every time you read this blog

Image by StockSnap from Pixabay

Arrays

Dummy Array Representation

An Array 🕳 is a basic storage unit that we as JS devs use. To get started with this blog, I would like to introduce !

Alex was on a journey to buy a car🚗 and he was using JS Arrays to store all the information that he collected during his research. In his journey, he met many people including dealers, salesmen, and individual owners. He grabbed all the information from them, analyzed it, and filtered them according to a few criteria.

1. Array Creation

To start with 🏁 he needs to initiate the array to store all his research.

    
    // 🌠 Simple way that we all use.
    let carsData = [];
    
    // Using a constructor to make an array.🌟
    let carsData = new Array();

Alex has his array ready and now heads to the market. He stops at a dealership named Dream Cars and meets Dany.

2. Finding Elements in an Array

👨‍💼 Dany is a guy with some cool cars under the roof. He has all the information with regards to cars in an Array. So he is taking Alex around the car lot and Alex spots a Red 🚗 car. Now Alex wants all the details of the car. Dany needs to search his car's Array. There are close to 100 cars in his lot. So searching is a task for him. He had made JS tools ready for such a situation and now he is looking for all the available versions of his software.

    let carLotInfo = [
        { id:1, model:'i20',make:'Hyundai', year:'2020', isSoldOut:false, priceTag:'₹5L'},
        { id:2, model:'Swift',make:'Maruti', year:'2018', isSoldOut:true, priceTag:'₹3.5L'},
        { id:3, model:'Rapid',make:'Skoda', year:'2019', isSoldOut:false, priceTag:'₹8L'},
        .
        .
        .
        { id:100, model:'F - Type',make:'Jaguar', year:'2021', isSoldOut:true, priceTag:'₹1.1CR'}
    ];

    // Native Approach - When Dany was new to JS
    function getCarDetailsAskedByClient(selectedCarModelId)  {
        for(let i = 0; i < 100; i ++)  {
            if(carLotInfo[idx].id === selectedCarModelId)  {
                return carLotInfo[idx];
            }  
        }
        /* Output -> { id:2, model:'Swift',make:'Maruti', year:'2018', isSoldOut:true, priceTag:'₹3.5L'} */
    
        // Now when Dany is power packed ⚡ with Array.prototype moethods
        return carLotInfo.find(car => car.id === selectedCarModelId);
        /* Output -> Same as above  */

        // The next Revision that Dany gives, keeping in mind 🤔 that if the client purchases the car.
        const carIdx = carLotInfo.findIndex(car => car.id === selectedCarModelId);
        return carLotInfo[carIdx];
        /* Output -> Same as above  */

        // LastIndexOf - also a searching function when multiple objects are present and last object is needed
        let data = [1,2,3,2,4,2,5];
        console.log(data.lastIndexOf(2));
        /* Output -> 5 */

        // Use cases when you just need to check whether an element exists in the array
        let data = ["Email1","Email2","Email3","Email4"];
        console.log(data.includes("Email3"));
        /* Output -> true */  
    }
    
    getCarDetailsAskedbyClient(2);

3. Adding Elements to an Array

Alex is quite convinced with the car. But still wishes to have a look around the lot for some family wagons 🚐 and sedans that have bold looks. Dany is glad that he has used the findIndex method, it is easy for him to give the details to Alex.

    function addCarsToData(car)  {
        let currentCarData = [{car1 info},{car2 info}];
        
        // As this is the first dealer - Conventional Method helps.
        currentCarData.push(car);
    
        /* Output -> 
        [{car1 info},{car2 info},
        { id:2, model:'Swift',make:'Maruti', year:'2018', isSoldOut:true, priceTag:'₹3.5L'}] */
    }

Alex looks around the lot and finalizes a couple of cars and now adds them to the array. They had a final talk regarding the finance and best offers. Alex said he will come back soon. Heading over, he meets Alina 👮‍♀️, a doctor in his neighborhood. She was moving to 🗽 the USA in the coming week and planned to sell her car. Her car was in top-notch condition and was a blazing yellow color sedan, but as she required ₹₹₹ she had a hefty price tag to it. Keeping in mind the offer given by Dany, Alex put his offer on priority.

    function addInfoOnPriority(danyInfo)  {
        carsData.unshift(danyInfo);
    }
// Output -> [[Dany's Car Details],[Alina's Car Details]]

4. Filling Data into an Array

Moving over, he went to Greg's Car Zone. Alex was a fan of AMG cars. Greg had all of the AMGs under his roof. He had them all carbon-fitted 🏴‍☠️ , custom colored🌈, and blazing wraps 🔥. Greg had 10 identical cars of 2018. Alex was going to the moon looking at his collection. Alex had to figure out a way to maintain consistency across the data.

    function fillArray(data)  {
        // Other way round of doing this.
        gregCarCollection = [{},{},{},data];
        
        for(let i = 0; i < 4; i++)  {
            // Copy Element at 0 from index 1
            gredCarCollection.copyWithin(i,4);
            /* Output -> [ {car_Info}, {car_Info} ] */
        }
        
        let gregCarCollection = [1,2,3,4];
        gregCarCollection.fill(data);
        /* Output -> [ {car_Info}, {car_Info}, {car_Info}, {car_Info} ]*/
    }

fill and copyWithin command work only when the array has some values

4. Size of an Array

Greg has a collection of 100s of cars out of which Alex had collected data for a specific number of cars. Now he needed to find the number of cars Alex had considered in his list.

    function NumberOfCars(gregCarCollection)  {
        return gregCarCollection.length; 
    }

5. Deleting Elements from an Array

Alex had a great day and returned home in the evening🥱. He went to his balcony, had a pint 🍺 , and looked into his carsInfo data collected today. He then realized that Alina's offer did not fit him well. He had to delete it.

    function deleteElement()  {
        
        // Delete the last element from the array
        let carsInfo = [1,2,3,4,5];
        carsInfo.pop();
        /* Output ->  [1,2,3,4] */
    
        // Delete the first element from the array 
        let carsInfo = [1,2,3,4,5];
        carsInfo.shift();
        /* Output -> [2,3,4,5] */
    
        // Delete an Element from a specified index
        let carsInfo = [2,7,12,5,18];
        let idx = carsInfo.findIndex(cars => cars === 5);
        carsInfo.splice(idx,1);
        /* Output -> [2,7,12,18] */
    
        // Delete Elements Based on some criteria
        let carsInfo = [2,7,12,5,18];
        carsInfo.filter((car,idx) => { return car > 10});
        /* Output -> [12,18] */
        
    }

6. Flattering Array

After looking at the data 😵. Alex was perplexed. It became an array of arrays and it was very difficult for him to perform basic operations. But fortunately, his grip over JS, helped him build a tool that can solve such problems.

    function flatternData()  {
        let carData = [[{data1}],[{data2}],[{data3}]];
        carData = carData.flat();
        /* Output -> [{data1},{data2},{data3}] */
    }

7. Iterating Over Array

Flattering has given a big relief 😌 to Alex. Now that the data was consistent, he wished to have a look at all the car information that he had collected 📚.

    function iterateOverArray(carsData)  {
        
        // Native Solution - for loop
        for(let i = 0; i < carsData.length; i++)  {
            console.log(carsData[i]);
        }
    
        // Using entries() as an Iterator
        for(const [idx,car] of carsData.entries())  {
            console.log(idx,car);
        }
    }

All multi-line codes are annoying ... Like us, even Alex was fed up of all the codes.

Tired Gif

Image by Rise at Seven from Giphy

JS has powerful functions that help achieve it easily and yes, as expected in single line codes.

    function iterateOverArray(carsData)  {
    
        // Using forEach
        carsData.forEach((data,idx) => console.log(data,idx));
    
        // Using map
        carsData.map((data,idx) => console.log(data,idx));
    
        // Using Filter
        carsData.filter((data,idx) => console.log(data,idx));
    }

🎈Note: map and filter return an array.

8. Filtering the Data inside Arrays

Alex was able to view all the data. Now he needed to filter out cars based on criteria such as price range, age of the car, and many more. map and filter is not just limited to iteration, they can do more than that.

    function filterOutContentFromArray(){
        let data = [
            {name:'Alto K10',age:9, price:'2L' , soldOut: true},
            {name:'Hyundai i20',age:1, price:'9L' , soldOut: true},
            {name:'Hyundai Creta',age:0, price:'20L' , soldOut: false},
            {name:'Toyota Yaris',age:3, price:'12L' , soldOut: true},
            {name:'Nissan GTR',age:6, price:'52L' , soldOut: false},
            {name:'Maruti Swift Dzire',age:2, price:'6L' , soldOut: true}
        ];
        
        // filter - Generates a new Array with elements that match a given criteria
        // Return the List of all the cars that are on sale
        let availableCars = data.filter((car,idx) => {return !car.soldOut});
        /* Output -> [ 
            {name:'Hyundai Creta',age:9, price:'20L' , soldOut: false},
            {name:'Nissan GTR',age:6, price:'52L' , soldOut: false}
        ]*/
    
    
        // Map - Generate a new Array with the power to manipulate existing elements
        // Its 2022 now, Update the age of the cars
        let updatedCarsInfo = data.map((car,info) => {return car.age + 1;});
        /* Output -> [
            {name:'Alto K10',age:10, price:'2L' , soldOut: true},
            {name:'Hyundai i20',age:2, price:'9L' , soldOut: true},
            {name:'Hyundai Creta',age:1, price:'20L' , soldOut: false},
            {name:'Toyota Yaris',age:4, price:'12L' , soldOut: true},
            {name:'Nissan GTR',age:7, price:'52L' , soldOut: false},
            {name:'Maruti Swift Dzire',age:3, price:'6L' , soldOut: true}
        ]*/ 
    
        // Reduce - Reduces the Array to a single value.
        // Count the number of cars that are aged not more than 4 years
        let count = data.reduce((finalCount,car) => {if(car.age <= 4) {return finalCount++;}});
        /* Output -> 4*/
    
        // The same scenerio as above
        let countRight = data.reduceRight((finalCount,car) => {if(car.age <= 4) {return finalCount++;}});
        /* Output -> 4*/
    }

🎈Note: reduce and reduceRight differ only in the direction of iteration.

reduce : left to right

reduceRight : right to left

9. Generating Sub Arrays

The next morning Alex was in trouble. 🤦‍♂️ Flattering and filtering had made it a task for Alex to separate car information given by Dany and Greg. But, Alex recalled that Dany gave him information of 10 cars which he had put on priority, out of which 6 were sold out. Now, he had to filter out the available cars.

    function getSubArray()  {
        let data = [
            {name:'Alto K10',age:9, price:'2L' , soldOut: false},
            {name:'Hyundai i20',age:1, price:'9L' , soldOut: false},
            {name:'Hyundai Creta',age:0, price:'20L' , soldOut: false},
            {name:'Toyota Yaris',age:3, price:'12L' , soldOut: false},
            {name:'Nissan GTR',age:6, price:'52L' , soldOut: false},
            {name:'Maruti Swift Dzire',age:2, price:'6L' , soldOut: false},
            {name:'Jaguar F-type',age:3, price:'1CR', soldOut: false},
            {name:'Ford Ecosport',age:5, price:'5L' , soldOut: false},
            {name:'Renault Scala',age:7, price:'6.5L' , soldOut: false},
            {name:'Honda CRV',age:4, price:'10L' , soldOut: false}
        ];
        
        let danysCarList = data.slice(0,4);
        /* Output -> [
            {name:'Alto K10',age:9, price:'2L' , soldOut: false},
            {name:'Hyundai i20',age:1, price:'9L' , soldOut: false},
            {name:'Hyundai Creta',age:0, price:'20L' , soldOut: false},
            {name:'Toyota Yaris',age:3, price:'12L' , soldOut: false}
        ]*/
    
        let gregsCarList = data.slice(4);
        /* Output -> [
            {name:'Nissan GTR',age:6, price:'52L' , soldOut: false},
            {name:'Maruti Swift Dzire',age:2, price:'6L' , soldOut: false},
            {name:'Jaguar F-type',age:3, price:'1CR' soldOut: false},
            {name:'Ford Ecosport',age:5, price:'5L' , soldOut: false},
            {name:'Renault Scala',age:7, price:'6.5L' , soldOut: false},
            {name:'Honda CRV',age:4, price:'10L' , soldOut: false}
        ]*/
    }

10. Sorting Arrays

Now Alex had information about the cars that Dany and Greg gave him. Alex preferred new cars and started sorting accordingly.

    function sortCarInfo()  {
        let data = [
            {name:'Alto K10',age:9, price:'2L' , soldOut: false},
            {name:'Hyundai i20',age:1, price:'9L' , soldOut: false},
            {name:'Hyundai Creta',age:0, price:'20L' , soldOut: false},
            {name:'Toyota Yaris',age:3, price:'12L' , soldOut: false},
            {name:'Nissan GTR',age:6, price:'52L' , soldOut: false},
            {name:'Maruti Swift Dzire',age:2, price:'6L' , soldOut: false},
            {name:'Jaguar F-type',age:3, price:'1CR', soldOut: false},
            {name:'Ford Ecosport',age:5, price:'5L' , soldOut: false},
            {name:'Renault Scala',age:7, price:'6.5L' , soldOut: false},
            {name:'Honda CRV',age:4, price:'10L' , soldOut: false}
        ];
    
        // To sort data in ascending order.
        data.sort((car1,car2) => { return car1.age - car2.age; });
        /* Output -> [
            {name:'Hyundai Creta',age:0, price:'20L' , soldOut: false},
            {name:'Hyundai i20',age:1, price:'9L' , soldOut: false},
            {name:'Maruti Swift Dzire',age:2, price:'6L' , soldOut: false},
            {name:'Toyota Yaris',age:3, price:'12L' , soldOut: false},
            {name:'Jaguar F-type',age:3, price:'1CR', soldOut: false},
            {name:'Honda CRV',age:4, price:'10L' , soldOut: false},
            {name:'Ford Ecosport',age:5, price:'5L' , soldOut: false},
            {name:'Nissan GTR',age:6, price:'52L' , soldOut: false},
            {name:'Renault Scala',age:7, price:'6.5L' , soldOut: false},
            {name:'Alto K10',age:9, price:'2L' , soldOut: false},
        ]*/
    
        // To sort data in descending order.
        data.sort((car1,car2) => {return car2.age - car1.age;}); 
    }

🎈Note: sort is in-place sorting and hence it doesnot return the sorted array.

reverse is also a sorting mechanism provided by JS. Read more about it here

11. Combining 2 Arrays

On his second day, he decided to buy a car from Dany. Dany had new cars arrived at his car lot on that day. Alex was interested in those cars and now needed the data of those cars to make a final call. Dany gave him all the information. Later on, Alex realized that Dany had given him information about some cars that he was not looking for. Now he needed to look for the data precisely. Thanks to JS tools that he built to help him handle such situations.

    function combineArrays()  {
        
        let data = ['content1','content2','content3'];
        let dataToCombine = ['content2','content4'];
    
        // Simple Method to combine 2 arrays
        console.log(data.concat(dataToCombine));
        /* Output -> ['content1','content2','content3','content2','content4'] */    

        // Using the Spread Operator
        data = [...data, ...dataToCombine];
        /* Output -> Same as above */
    
        // Combine only the unique values
        data = [... new Set(data.concat(dataToCombine))];
        /* Output -> ['content1','content2','content3','content4'] */
    }

12. Miscellaneous

Finally, he had the CarInfo ready. Alex sent an email to Dany attaching the information of the car he was willing to buy.

    // Convert Array to String
    let ar = ['name','@','email','.com'];
    console.log(ar.join());
    /*Output -> 'name@email.com' */

    // Convert String to Array
    let str = "React_Dev";
    console.log(Array.from(str));
    /* Output -> ["R", "e", "a", "c", "t", "_", "D", "e", "v"] */

    // Check if the given input is array 
    
    console.log(Array.isArray(str));
    /* Output -> false (str is a string) */
    
    console.log(Array.isArray(ar));
    /* Output -> true */

Using all the JS tools , Alex was able to buy a car of his choice.

Alex's Car

Image by Off the Jacks from Giphy

Hope this blog was a fun read. A fun fact, all these cheats, and hacks that I have written here are core concepts of JS Arrays. I just tried putting them in a simple way. All thanks ✨ to Alex, Alina, Dany and Greg.

Alex's Car

Image by no_user2 from Tenor

Find the links for the next blogs here.

#2 Js Cheats - Objects
#3 Js Cheats - Strings

.


Written by Yashwin

Do you want to know when I post something new?
Then subscribe to my newsletter.