# Logical Approach to Common Problems

`from a single arrayfrom a array of objects JavaScript`

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ ✦ ✦ ✦ ▬▬▬▬▬▬▬▬▬▬▬▬▬▬

# ◉ Check for Prime No.

`function test_prime(n) {  if (n === 1) {    return false;  } else if (n === 2) {    return true;  } else {    for (var x = 2; x <= n/2; x++) { # we cannot start with 3 as in that case the test for 4 will fail.      if (n % x === 0) {        return false;      }    }    return true;  }}console.log(test_prime(37));  # true`

You can also decrease the complexity of the algorithm from `O(n)` to `O(sqrt(n))` if you run the loop until square root of a number:

With the ES6 syntax:

`const isPrime = num => {    if (num === 1) return false;    for(let i = 2, s = Math.sqrt(num); i <= s; i++)        if(num % i === 0) return false;     return num > 1;}`

# ◉ print all prime no.s between 2 to 100

`const isPrime = num => {   let count = 2;   while(count < (num / 2)+1){      if(num % count !== 0){         count++;         continue;      };      return false;   };   return true;};const primeBetween = (a, b) => {   let count = 0;   for(let i = Math.min(a, b); i <= Math.max(a, b); i++){      if(isPrime(i)){         count++;      };   };   return count;};console.log(primeBetween(2, 21));`

# ◉ Fibonacci series

1,1,2,3,5,8,13,21,34,55,89

`var i;var fib = []; fib[0] = 0;fib[1] = 1;for (i = 2; i <= 10; i++) {  fib[i] = fib[i - 2] + fib[i - 1];  console.log(fib[i]);}console.log(fib);# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]`

# ◉ Factorial using Recursion

5! = 5 * 4 * 3 * 2 * 1

`function factorial(num) {   if (num == 1 || num == 0) {     return 1   }   return num * factorial(num - 1)}console.log(factorial(5));  # 120`

# Recursion

A recursive function is a function that calls itself.

Another example of recursion:

`const count = (i) => {  if (i === 10) {    return;  }  console.log(i);  count(i + 1);}count(0);`

In the code above, we have a simple recursive function that stops with `i` reaches 10.

For each value of `i` , we log the value of `i` to the console.

# ◉ Palindrome using For loop

`function palindrome(str) { var re = /[^A-Za-z0-9]/g; str = str.toLowerCase().replace(re, '');var len = str.length; for (var i = 0; i < len/2; i++) {   if (str.charAt(i) !== str.charAt(len - 1 - i) {       return false;   } } return true;   # return true is at end of for loop}palindrome("A man, a plan, a canal. Panama");`

# ◉ Removing Duplicates from a single Array

The easiest way in my opinion but only supported with ES6.

`const arr = [2,3,4,2,3,4]const uniqueSet = new Set(arr);const backToArray = [...uniqueSet]`

`Set` is a new data object introduced in ES6. Because `Set` only lets you store unique values. When you pass in an array, it will remove any duplicate values.

Once the duplicates are gone, we’re going to convert it back to an array by using the spread operator `...`

Note: If you had an array containing objects, functions or additional arrays, you’d need a different approach!

`function removeDuplicates(array) {  let obj = {};  array.forEach(function(i) {    if(!obj[i]) {      obj[i] = true    }  })  return Object.keys(obj);};`

Checks to see if each element in the array is unique.

`function removeDuplicates(array) {  return array.filter((eachItem, index, array) =>              array.indexOf(eachItem) === index)};// removes the duplicate ones and return only unique values.To find only the duplicates, just reverse the condition as below:array.indexOf(eachItem) !== index)`
`function removeDuplicates(array) {  let a = []   array.map(x =>     if(!a.includes(x) {      a.push(x)    })  return a};`

Maps through the array and adds unique elements to a new array.

# ◉ Remove duplicates from a array of objects JavaScript

Recommended method:

`const arr = [   {      "roll_no": 1,      "name": "anil"   },   {      "roll_no": 2,      "name": "sujata"   },   {      "roll_no": 1,      "name": "anil"   },   {      "roll_no": 1,      "name": "anil"   }   ];   const obj = {};   const newArray = [];   arr.forEach(el => {      if(!obj[JSON.stringify(el)]){         obj[JSON.stringify(el)] = true;         newArray.push(el);   }});console.log(newArray);[   { roll_no: 1, name: 'anil' },   { roll_no: 2, name: 'sujata' }]`

Other method:

`var values = [    { name: 'someName1' },    { name: 'someName2' },    { name: 'someName4' },    { name: 'someName2' }];var valueArr = values.map(function(item){ return item.name });console.log(valueArr);var isDuplicate = valueArr.some(function(item, idx){         return valueArr.indexOf(item) != idx });console.log(isDuplicate);`

# ◉ Find if 2 arrays contain any common item ?

✍ Method 1:

Time Complexity: O(M + N): (Recommended method)

`const arr1 = ['a', 'b', 'c', 'd']; const arr2 = ['e', 'f', 'g'];function findCommonElements2(arr1, arr2) {let obj = {};     for (let i = 0; i < arr1.length; i++) {         if(!obj[arr1[i]]) {             const element = arr1[i];              obj[element] = true;             console.log(obj) ;            }     }     for (let j = 0; j < arr2.length ; j++) {         if(obj[arr2[j]]) {             return true;  # "duplicate found"        }     }     return false;         # "NO duplicate found"}findCommonElements2(arr1, arr2);`

✍ Method 2 :

Time Complexity: O(M * N):

`const array1 = ['a', 'b', 'c', 'd']; const array2 = ['k', 'x', 'z'];   function findCommonElement(array1, array2) {           for(let i = 0; i < array1.length; i++) {         for(let j = 0; j < array2.length; j++) {             if(array1[i] === array2[j]) {                 return true;             }         }     }     // Return if no common element exist     return false;  } findCommonElement(array1, array2);`

✍ Method 3:

`array1 = array1.filter(function(val) {  return array2.indexOf(val) === -1;});`

# ◉ Sort an array using w/o using any inbuilt method.

`function sorter(array){    var count = array.length - 1,        swap,        i,        j;    for (i = 0; i< count; i++)    {      for (j = 0; j< count; j++)        {         if (array[j] > array[j + 1])            {                swap = array[j + 1];                array[j + 1] = array[j];                array[j] = swap;            }        }    }    return array;}console.log(sorter([1, 0, 1, 1, 0, 0, 1]));#Result: [0,0,0,1,1,1,1];`
`const months = ['March', 'Jan', 'Feb', 'Dec'];months.sort();console.log(months);// output: Array ["Dec", "Feb", "Jan", "March"] as expected.const array1 = [1, 30, 4, 21, 100000];array1.sort();console.log(array1);// output: Array [1, 100000, 21, 30, 4] but not as expected.`

To compare numbers instead of strings, the compare function can simply subtract `b` from `a`. The following function will sort the array in ascending order (if it doesn't contain `Infinity` and `NaN`):

`var numbers = [4, 2, 5, 1, 3];numbers.sort(function(a, b) {  return a - b;});console.log(numbers);// [1, 2, 3, 4, 5]# using ES6 methodlet numbers = [4, 2, 5, 1, 3];numbers.sort((a, b) => a - b);console.log(numbers);// [1, 2, 3, 4, 5]`
`var items = [  { name: 'AAA', value: 4 },  { name: 'BBB', value: 3 },  { name: 'CCC', value: 1 },    { name: 'DDD', value: 2 }];// sort by value (which is integer)items.sort(function (a, b) {  return a.value - b.value;});console.log(items);// sort by name (which is string)items.sort(function(a, b) {  var nameA = a.name.toUpperCase(); // ignore upper and lowercase  var nameB = b.name.toUpperCase(); // ignore upper and lowercase    if (nameA > nameB) {    return 1;  }  if (nameA < nameB) {    return -1;  }  // names must be equal  return 0;});console.log(items);items     .filter(eachItem => eachItem.value > 2).sort((a, b) => a.value - b.value)     .map(eachItem => console.log(eachItem.name + ':' + eachItem.value));`

Algorithm

1. Declare an array and input the array elements.
2. Start traversing the array and if the current element is negative, swap the current element with the first positive element and continue traversing until all the elements have been encountered.
3. Print the re-arranged array.

OR

`var t = [2, -12, 4, 46, -20, -1];var positiveArr = [];var negativeArr = [];t.forEach(function(item) {  if (item < 0) {    negativeArr.push(item);  } else {    positiveArr.push(item)  }});console.log(positiveArr) // should output [5, 6, 1]console.log(negativeArr)`

OR

`var t = [2, -12, 4, 46, -20, -1];var positiveArr = t.filter((elem) => elem > 0);var negativeArr = t.filter((elem) => elem < 0);var result = negativeArr.concat(positiveArr);`

OR

`var arr = [2, -12, 4, 46, -20, -1],    res = arr.reduce(function(s,a) {      a <= 0 ? s.unshift(a) : s.push(a);      return s;    }, []);        console.log(res);`

NOTE: Do you not realise that just `sorting` the array already does this “negative at the start, positive at the end” thing?

# ◉ Compare two JavaScript array

✍ Method 1:

`var arr1 = [1, 3, 7, 5]; var arr2 = [1, 3, 5, 7];function compare(arr1, arr2) {             arr1.sort();             arr2.sort();                           if(arr1.length != arr2.length)                 return false;                           for(var i = 0; i < arr1.length; i++) {                 if (arr1[i] != arr2[i])                     return false;             }             return true;         }     compare(arr1, arr2)`

Caveat: sort() doesn’t produce incorrect result when sorting numbers.

# ◉ Compare two Objects

2 objects (with same keys & same values)

• Use JSON.stringify() function to convert object into JSON string.
• Now compare both JSON string using comparison operator (==) to check both array objects are equal or not.
`var arr1 = [             {id: "1", name: "GeeksforGeeks"},              {id: "2", name: "GFG"}    ];               var arr2 = [             {id: "1", name: "GeeksforGeeks"},             {id: "2", name: "GFG"}    ];function compare(ar1, ar2) {         if(JSON.stringify(arr1) === JSON.stringify(arr2)){             return true;         }         else             return false;         }compare(arr1, arr2);`

Note: This method works only when both array objects sorted into the same fashion.

2 objects (with different keys & same values)

There is no direct method in javascript to check whether two objects have the same data or not. however, below is the Pseudo Code:

`function hasSameData    if both objects have the same number of keys (properties)        if every key of obj1 matches with the corresponding key         of obj2 and values of the same keys of both objects match.            return true    return falseconst obj1 = {        name: 'Ram',        age: 21    };      const obj2 = {        name: 'Ram',        roll_no: 21    };      const haveSameData = function (obj1, obj2) {        const obj1Length = Object.keys(obj1).length;        const obj2Length = Object.keys(obj2).length;          if (obj1Length === obj2Length) {            return Object.keys(obj1).every(                key => obj2.hasOwnProperty(key)                    && obj2[key] === obj1[key]);        }        return true;    };console.log(haveSameData(obj1, obj2));`
`let isMatchingBrackets = function (str) {    let stack = [];    let map = {        '(': ')',        '[': ']',        '{': '}'    }    for (let i = 0; i < str.length; i++) {        // If character is an opening brace add it to a stack        if (str[i] === '(' || str[i] === '{' || str[i] === '[' ) {            stack.push(str[i]);        }        //  If that character is a closing brace, pop from the stack, which will also reduce the length of the stack each time a closing bracket is encountered.        else {            let last = stack.pop();            //If the popped element from the stack, which is the last opening brace doesn’t match the corresponding closing brace in the map, then return false            if (str[i] !== map[last]) {return false};        }    }    // By the completion of the for loop after checking all the brackets of the str, at the end, if the stack is not empty then fail        if (stack.length !== 0) {return false};    return true;}console.log(isMatchingBrackets("(){}")); // returns trueconsole.log(isMatchingBrackets("[{()()}({[]})]({}[({})])((((((()[])){}))[]{{{({({({{{{{{}}}}}})})})}}}))[][][]")); // returns trueconsole.log(isMatchingBrackets("({(()))}}"));  // returns false`
`const arr1 = [1, 2, [3, 4]];arr1.flat(); // [1, 2, 3, 4]const arr2 = [1, 2, [3, 4, [5, 6]]];arr2.flat();// [1, 2, 3, 4, [5, 6]]const arr3 = [1, 2, [3, 4, [5, 6]]];arr3.flat(2);// [1, 2, 3, 4, 5, 6]const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];arr4.flat(Infinity);// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]const arr5 = [1, 2, , 4, 5];arr5.flat();// [1, 2, 4, 5]`

# Alternatives

`const arr = [1, 2, [3, 4]];// To flat single level arrayarr.flat();// is equivalent tolet result = arr.reduce((acc, val) => acc.concat(val), []);console.log(result) // [1, 2, 3, 4]console.log(arr) // [1, 2, [3, 4]]// or with decomposition syntaxconst flattened = arr => [].concat(...arr);`

# ◉ find the max / min number in an array

`const nums = [1, 2, 3]Math.min(nums) // NaNMath.max(nums) // NaN`

That is because Math.min or Math.max functions expect distinct variables and not an array. So, in order to do that before ES6/ES2015 apply method was used.

`var nums = [1, 2, 3]Math.min.apply(Math, nums) // 1Math.max.apply(Math, nums) // 3Math.min.apply(null, nums) // 1Math.max.apply(null, nums) // 3`

With ES6/ES2016 destructuring assignment it becomes easier

The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables.

`const nums = [1, 2, 3]Math.min(...nums)    // 1Math.max(...nums)    // 3`
`var arr = [3, 6, 2, 56, 32, 5, 89, 32];var largest = arr[0];for (var i = 0; i < arr.length; i++) {    if (largest < arr[i] ) {        largest = arr[i];    }}console.log(largest);`

NOTE:- Above can be done using built-in functions map() + Math.max()

# ◉ union of 2 arrays

Method 1:

• Store all elements in a JavaScript object.

Storing elements in JavaScript Object is going to remove the duplicate elements.

• At the end, push all element in a JavaScript array.
`function computeUnion(a, b) {     var object = {};             for (var i = a.length-1; i >= 0; --i)         object[a[i]] = a[i];             for (var i = b.length-1; i >= 0; --i)         object[b[i]] = b[i];             var ret = []             for (var i in object) {         if (object.hasOwnProperty(i))         ret.push(object[i]);     }     return ret; }`

Method 2 :

`var union = [...new Set([...A, ...B])];`

# ◉ merge 2 Javascript objects

`function extend(src, dest) {    for (var key in dest) {       if (dest.hasOwnProperty(key)){             src[key] = dest[key];       }    }    return src;}// examplevar a = { foo: true, name: "anil", gender: "male"}; var b = { bar: false, gender: "female", age: 30 };var c = extend(a, b);console.log(c);# {"foo":true,"name":"anil","gender":"female","bar":false,"age":30}`
`function changeAgeAndReference(person) {    person.age = 25;    person = {        name: 'John',        age: 50    };        return person;}var personObj1 = {    name: 'Alex',    age: 30};var personObj2 = changeAgeAndReference(personObj1);console.log(personObj1); // -> { name: 'Alex', age: 25 }console.log(personObj2); // -> { name: 'John', age: 50 }`

The variable `person` in the function contains a reference to the `personObj1` object, so initially it acts directly on that object.

Once we reassign `person` to a new object, it stops affecting the original.

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -

Output is : Brooke Jonas Dennis 2020 TR

Why? In JS, by default all properties of obj are sorted in following order:

ascending order for number-like keys < string keys

— — — — — — — — — — — — — — — — — — — — — — — — — — — —

# ◉ Sum of no.s using rest operator and reduce()

Javascript, `rest` parameter syntax allows us to show an indefinite number of arguments as an array and reduce method is used for reduce array to a single value.

Here, `args` convert all arguments passed to a function as an array, so you can use reduce() which only applies to an array.

`let arr = [10,20,30,40,50];let [a, b, c, ...d] = arr;console.log(d);  // [40, 50];`

When there is a rest parameter we should pass an array as an argument so the answer is [40, 50].

The spread operator (…) allows an expression to be expanded in places where multiple elements/variables/arguments are expected.

When we use the spread operator within `Math.min()` it will expand, or spread out, our array and insert each variable as a separate parameter into `Math.min()`!

In other words:

`Math.min(...[1,2,3,4])` is the same as `Math.min(1,2,3,4)`

— — — — — — — — — — — — — — — — — — — — — — — — — — —

# ◉ 3 ways to SWAP variables in JS :

Let’s swap the variables `a` and `b` using destructuring assignment:

`let a = 1;let b = 2;[a, b] = [b, a];a; // => 2b; // => 1`

`[a, b] = [b, a]` is the de-structuring assignment that swaps the variables `a` and `b`.

Let’s swap the values of variables `a` and `b` using a temporary variable `temp`:

`let a = 1;let b = 2;let temp;temp = a;a = b;b = temp;a; // => 2b; // => 1`

You can swap variables without the use of additional memory (like a temporary array or variable).

`let a = 1;let b = 2;a = a + b; // this is trickiest oneb = a - b;a = a - b;a; // => 2b; // => 1`
`console.log((variable !== null) && (variable.constructor === Object));`

above returns `false` for nulls, arrays, and functions, but `true` for objects.

`var obj = {a: 1, b: 2, undefined: 1};Object.keys(obj).reduce(function(a, b){     return obj[a] > obj[b] ? a : b });`
`variable.constructor === Array`

Some other ways are:

`Array.isArray(variable)`
`arr.slice(0);`
`arr.slice(1);`
`arr.slice(-1);`
`//arr = ["A", "B", "C", "D"];console.log(arr.toString()); // "A,B,C,D"console.log(arr + "");       // "A,B,C,D"console.log(arr.join());     // "A,B,C,D"console.log(arr.join('+'));  // A+B+C+D`

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

## More from Anil Kumar

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.