Arrays in JavaScript

Posted on by By Nikhilesh, in Business Intelligence, Front End, Helical Insight, Javascript | 0

Here is the question.
Suppose you are given two arrays as key, value pairs and asked you to associate them as Object with the same, who would you do that? So, here is the solution for it.

    function associateArrays(keys, values) {
        if(!Array.isArray(keys) || !Array.isArray(values)) {
            throw new TypeError("Expected two Arrays");
        }
        var result = {};
        for(var i = 0; i < keys.length; i++) {
            result(keys[i]) = values[i];
        }
        return result;
    }

 

    var split = associateArrays(["0", "1", "2"], ["a", "b", "c"]);
    split;
    //Object {0: "a", 1: "b", 2: "c"}

Here is another question.
Suppose say that you are given an array and asked to multiply each item in the array and return the result. SO here is the solution for it.

    function multipleArrayItems(arr) {
        if(!Array.isArray(arr)) {
            throw new TypeError("Expected an array");
        }
        if(arr.length < 2) {
            throw new TypeError("The array should at least have 2 items");
        }
        var product = arr[0];
        for(var i = 0; i < arr.length; i++) {
            product *= arr[i];
        }
        return product;
    }

 

    var product = multipleArrayItems([2, 2, 4, 4]);
    product; // 64

 

-By
Uma Maheswar
Helical IT Solution

logo

Best Open Source Business Intelligence Software Helical Insight is Here

logo

A Business Intelligence Framework

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments