Logical Approach to Common Problems

πŸ“„ Table of contents

➀ Misc

➀ SUM

➀ Array

➀ SORT

➀ COMPARE

➀ Objects

➀ Strings

β—‰ 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
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;
}

β—‰ Fibonacci series

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

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

β—‰ 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;
}
palindrome("A man, a plan, a canal. Panama");

β—‰ Removing Duplicates from a single Array

1. Set

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

2. forEach()

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

3. filter()

function removeDuplicates(array) {
return array.filter((eachItem, index) => array.indexOf(eachItem) === index)
};

4. map()

function removeDuplicates(array) {
let a = []
array.map(x =>
if(!a.includes(x) {
a.push(x)
})
return a
};

β—‰ Remove duplicates from a array of objects JavaScript

const arr = [
{
"roll_no": 1,
"name": "anil"
},
{
"roll_no": 2,
"name": "sujata"
},
{
"roll_no": 1,
"name": "anil"
},
{
"roll_no": 1,
"name": "anil"
}
];
const x = {};
const newArray = [];
arr.forEach(el => {
if(!x[JSON.stringify(el)]){
x[JSON.stringify(el)] = true;
newArray.push(el);
}
});
console.log(newArray);[
{ roll_no: 1, name: 'anil' },
{ roll_no: 2, name: 'sujata' }
]
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 ?

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);
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);

Removing Duplicate(s) from two Arrays

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];

β—‰ using inbuilt β€œsort()” method

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]
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]

β—‰ Sort an array of objects based on some property

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));

β—‰ Rearrange positive and negative numbers in an array

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)
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);
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

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)

β—‰ Compare two Objects

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);
const 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 "adsfasdfasdf";
};
console.log(haveSameData(obj1, obj2));

β—‰ Count the occurrence of each character in a string

var str = "count number of each char in this string";var counts = {};// Misc vars
var ch, index, len, count;
for (index = 0, len = str.length; index < len; ++index) {
ch = str.charAt(index);
count = counts[ch];
console.log("count =>"+ count); // "count =>undefined"
counts[ch] = count ? count + 1 : 1;
}
for (ch in counts) {
console.log(ch + " ==>: " + counts[ch]);
}

β—‰ Array.prototype.reduce()

const array1 = [1, 2, 3, 4];
const reducer = (accu, currValue) => accu + currValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

β—‰ balanced parenthesis

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 true
console.log(isMatchingBrackets("[{()()}({[]})]({}[({})])((((((()[])){}))[]{{{({({({{{{{{}}}}}})})})}}}))[][][]")); // returns true
console.log(isMatchingBrackets("({(()))}}")); // returns false

β—‰ Flattening nested arrays

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

β—‰ reduce and concat

const arr = [1, 2, [3, 4]];// To flat single level array
arr.flat();
// is equivalent to
arr.reduce((acc, val) => acc.concat(val), []);
// [1, 2, 3, 4]
// or with decomposition syntax
const flattened = arr => [].concat(...arr);

β—‰ reverse a string using inbuilt methods

function reverseString(str) {
return str.split("").reverse().join("");
}
reverseString("hello");

β—‰ reverse an INTEGER using inbuilt methods

let myNumber = 23;
let myChar = myNumber.toString().split('').reverse().join('');
console.log(myChar) // returns 32;
console.log(typeof(myChar)) // returns string
const myNewNumber = parseInt(myChar);console.log(myNewNumber); // returns 32
console.log(typeof(myNewNumber)) // returns number

β—‰ find the max / min number in an array

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

old traditional approach:

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);

β—‰ union of 2 arrays

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;
}
var union = [...new Set([...A, ...B])];

β—‰ merge 2 or more Javascript Arrays

β—‰ 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}

β—‰ Pass by value vs Pass by Reference:

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 }

β—‰ Sum of no.s using rest operator and reduce()

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

β—‰ 3 ways to SWAP variables in JS :

1. De-structuring assignment

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

2. Using β€œthird” variable

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

3. Addition and difference

let a = 1;
let b = 2;

a = a + b;
b = a - b;
a = a - b;
a; // => 2
b; // => 1

β—‰ check if a variable is an Object {}

console.log((variable !== null) && (variable.constructor === Object));

β—‰ check if a variable is an array

variable.constructor === Array
Array.isArray(variable)

β—‰ Clone an Array:

arr.slice(0);

β—‰ get last element of an Array:

arr.slice(-1);

β—‰ join all elements of an array:

//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.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store