Recently while preparing for a javascript interview I revised foundational questions of javascript and shared a few goods with you.
1. Check if an object is an array.
let arr = [1,2,3,4,5]
// METHOD 1
console.log(toString.call(arr) === "[object Array]"); // true
console.log(toString.apply(arr) === "[object Array]"); // true
console.log(toString.apply(arr) === "[object Array]"); // true
console.log(toString.bind(arr)() === "[object Array]"); // true
// METHOD 2
console.log(Array.isArray(arr)); // true
// METHOD 3
console.log(Object.prototype.toString.call(arr) === "[object Array]");
// true
2. Clone an array.
// Changing clone array would not affect original array
let arr = [10, 20, 30, 40, 50]
// METHOD 1
let clone_arr = arr.slice()
clone_arr[1] = 1
console.log(`arr: ${arr} | clone_array: ${clone_arr}`);
// arr: 10,20,30,40,50 | clone_array: 10,1,30,40,50
// METHOD 2
let clone_arr1 = Array.from(arr)
clone_arr1[1] = 1
console.log(`arr: ${arr} | clone_array1: ${clone_arr1}`);
// arr: 10,20,30,40,50 | clone_array1: 10,1,30,40,50
// METHOD 3
let clone_arr2 = [... arr]
clone_arr2[1] = 1
console.log(`arr: ${arr} | clone_array2: ${clone_arr1}`);
// arr: 10,20,30,40,50 | clone_array2: 10,1,30,40,50
// OTHERS::
let clone_arr3 = arr.map(i => i)
let clone_arr4 = arr.filter(i => i)
let clone_arr5 = arr.filter(() => true)
3. Return first 'n' elements of array
const firsts = (arr, k=1) => {
console.log(k);
if(k>=0){
return arr.slice(0,k);
}
return []
}
console.log(firsts([7, 9, 0, -2])); // [7]
console.log(firsts([],3)); // []
console.log(firsts([7, 9, 0, -2],3)); // [7, 9, 0]
console.log(firsts([7, 9, 0, -2],6)); // [ 7, 9, 0, -2 ]
console.log(firsts([7, 9, 0, -2],-3)); // []
4. Return the last 'n' elements of an array
const lasts = (arr, k=1) => {
console.log(k);
if(k>=0){
return arr.slice(arr.length-k);
}
return []
}
console.log(lasts([7, 9, 0, -2])); // [2]
console.log(lasts([7, 9, 0, -2],3)); // [9, 0, 02]
console.log(lasts([7, 9, 0, -2],6)); // [ 0, -2 ]
console.log(lasts([7, 9, 0, -2],-3)); // []
5. Add hyphens between two evens
const addHyphenBetweenTwoEvens = (nums) => {
nums = Array.from(nums.toString());
let result = [nums[0]]
for(let x=1; x<nums.length; x++)
{
if((nums[x-1]%2 === 0)&&(nums[x]%2 === 0))
{
result.push('-', nums[x]);
}
else
{
result.push(nums[x]);
}
}
return result.join("");
}
console.log(addHyphenBetweenTwoEvens("025468")); //0-254-6-8
6. program to find the most frequent item of an array
const mostFrequent = (arr) => {
let m = new Map();
for (let x of arr){
if(m.has(x)){
m.set(x, m.get(x)+1)
}
else{
m.set(x, 1)
}
}
console.log(Math.max(... m.values()));
let mx = Math.max(... m.values())
const mxVal = [...m].find(([k, v]) => v == mx );
return `${mxVal[0]} ( ${mxVal[1]} times )`
}
console.log(mostFrequent([3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3]));
// TC = SC = O(n), where n is the length of the input array.
7. Swap the case of each character
const caseSwapping = (string) => {
let revStr = ""
for(let x=0; x<string.length; x++){
if(string[x] == string[x].toUpperCase()){
revStr += string[x].toLowerCase()
}
else{
revStr += string[x].toUpperCase()
}
}
return revStr
}
console.log(caseSwapping("The Quick Brown Fox"));
// TC = SC = O(n)
8. Program to find the sum of squares of a numeric vector
const sumOfSquares = (arr) => {
let sums = arr.map(x => x**2)
.reduce((a,b) => a+b, 0)
return sums
}
console.log(sumOfSquares([0,1,2,3,4])) // 30
9. Sum of each index value of two or more arrays
let array1 = [1,0,2,3,4];
let array2 = [3,5,6,7,8,13];
let mx = Math.max(array1.length, array2.length)
let res = []
for(let x=0; x<mx; x++){
if(array1[x] && array2[x]){
res.push( array1[x] + array2[x])
}
else if(array1[x]){
res.push(array1[x])
}
else if(array2[x]){
res.push(array2[x])
}
}
console.log(res); //[ 4, 5, 8, 10, 12, 13 ]
10. Shuffle an array
let randomizeArr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
randomizeArr.sort((a, b) => 0.5-Math.random(), 0)
console.log(randomizeArr); // [ 7, 6, 9, 5, 1, 0, 4, 8, 3, 2 ]
11. Binary search
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const binarySearch = (arr, k) => {
let start = 0, end = arr.length-1;
while(start<end){
let mid = parseInt((end - start) / 2)
if(arr[mid] < k)
start = mid+1
else if(arr[mid] > k)
end = mid-1
else
return mid
}
}
console.log(binarySearch(arr, 3));
12. Return all leap years under the given range
const isLeapYear = (year) => {
if( (year % 4 === 0 && year%100 !==0)
|| (year%100 === 0 && year%400 === 0)
){
return year
}
return false
}
const leapYearRange = (startDate, endDate) => {
let res = []
for(let x=startDate; x<=endDate; x++){
if(isLeapYear(x))
res.push(x)
}
return res
}
console.log(leapYearRange(2000, 2012)); // [ 2000, 2004, 2008, 2012 ]
13. Flatten an array
const flatten = (arr, shallow, res) => {
if(!res) res = []
if(shallow) {return res.concat.apply(res, a);}
for(let x=0; x<arr.length; x++){
if (Array.isArray(arr[x])){
flatten(arr[x], shallow, res)
}else{
res.push(arr[x])
}
}
return res
}
let arr = [1, [2], [3, [[4]]],[5,6]]
console.log(flatten([1, [2], [3, [[4]]],[5,6]])); // [ 1, 2, 3, 4, 5, 6 ]
// A LAME METHOD
console.log(arr.flat(10)) // [ 1, 2, 3, 4, 5, 6 ]
//ANOTHER AMAZING METHOD âš¡
console.log(arr.toString().split(",").map(Number));// [ 1, 2, 3, 4, 5, 6 ]
14. Union of two array / find the unique elements from two arrays
let arr1 = [1,2,3,3]
let arr2 = [4,5,6]
// METHOD 1
let res = [... new Set(arr1.concat(arr2))]
res; // [ 1, 2, 3, 4, 5, 6 ]
// METHOD 2
let res1 = []
arr1.forEach(x => !res1.includes(x) ? res1.push(x): "")
arr2.forEach(x => !res1.includes(x) ? res1.push(x): "")
res1 // [ 1, 2, 3, 4, 5, 6 ]
15. Find the difference of two arrays.
let arr1 = [1,2,3,3]
let arr2 = [4,[[5]],6]
const difference = (arr1, arr2) => {
let res = []
// flatten array (precautions🩺)
arr1 = arr1.toString().split(',').map(Number)
arr2 = arr2.toString().split(',').map(Number)
arr1.forEach(x => !arr2.includes(x) ? res.push(x): "")
arr2.forEach(x => !arr1.includes(x) ? res.push(x): "")
return res
}
console.log(difference([1, 2,3, 3], [4,[[5]],6])) // [ 3, 100, 10 ]
console.log(difference([1, 2, 3], [100, 2, 1, 10])) // [ 3, 100, 10 ]
console.log(difference([1, 2, 3, 4, 5], [1, [2], [3, [[4]]],[5,6]])); // [6]
16. Function to remove. 'null', '0', '""', 'false', 'undefined' and 'NaN' values from an array
const cleansing = (arr) => {
// 1st WAY
/**
* let res = []
* for(let x of arr){
* if(x){
* res.push(x);
* }
* }
* return res;
*
*/
//2nd WAY
return arr.filter(i => i)
}
console.log(cleansing([NaN, 0, 15, false, -22, '',undefined, 47, null]));
//[ 15, -22, 47 ]
17. Sort the specified array of objects by title value
var library = [
{ author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254},
{ author: 'Steve Jobs', title: 'Walter Isaacson', libraryID: 4264},
{ author: 'Suzanne Collins', title: 'Mockingjay: The Final Book of The Hunger Games', libraryID: 3245}
]
library.sort((a, b) => {
if(a.title < b.title) return -1
if(a.title > b.title) return 1
return 0
})
library
/*
[ { author: 'Suzanne Collins',
title: 'Mockingjay: The Final Book of The Hunger Games',
libraryID: 3245 },
{ author: 'Bill Gates',
title: 'The Road Ahead',
libraryID: 1254 },
{ author: 'Steve Jobs',
title: 'Walter Isaacson',
libraryID: 4264 } ]
*/
18. Pair Sum
const pairSum = (arr, k) => {
let m = {}
for (const [i, x] of arr.entries()){
if(k-x in m){
return [m[k-x], i].toString()
}
else{
m[x] = i
}
}
}
console.log(pairSum([1,2,3,4,5], 5)); // [1,2]
19. Retrieve the value of a given property from all elements in an array
const library = [
{ author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254},
{ author: 'Steve Jobs', title: 'Walter Isaacson', libraryID: 4264},
{ author: 'Suzanne Collins', title: 'Mockingjay: The Final Book of The Hunger Games', libraryID: 3245}
];
console.log(library.map(x => Object.values(x)));
// OUTPUT
// [ [ 'Bill Gates', 'The Road Ahead', 1254 ],
// [ 'Steve Jobs', 'Walter Isaacson', 4264 ],
// [ 'Suzanne Collins','Mockingjay: The Final Book of The Hunger Games', 3245 ]
// ]
20. Fill the array
const fillArray = (start, end, freq) => {
let res= []
if (typeof start === "string"){
start = start.charCodeAt(0)
end = end.charCodeAt(0)
for(let i=start; i< end; i+= freq){
res.push(String.fromCharCode(i));
}
}
else{
for(let i=start; i< end; i+= freq){
res.push(i);
}
}
return res;
}
console.log(fillArray(1,10,2)) // [ 1, 3, 5, 7, 9 ]
console.log(fillArray('a','z',2)) // [ 'a', 'c', 'e', 'g', 'i', 'k', 'm', 'o', 'q', 's', 'u', 'w', 'y' ]
21. Remove specific element from array
let arr = [2, 5, 9, 6], k= 5;
arr.splice(arr.indexOf(k),1);
console.log(arr); // [ 2, 9, 6 ]
22. Return an array of specified length, filled with integer numbers, increase by one from starting position
// 1st WAY : SIMPLE FOR LOOP AND ADD VALUE TO ARRAY
const fillArray = (start, freq) => {
let res = []
for(let i=start; i<start+freq; i++){
res.push(i)
}
return res
}
console.log(fillArray(1,4)); //[ 1, 2, 3, 4 ]
console.log(fillArray(-6,4)); // [ -6, -5, -4, -3 ]
// 2nd WAY : MANIPULATE HOW Array.from USUABILITY âš¡
const fillArray1 = (start, freq) => {
return Array.from({length:freq}, (v, i) => i+start);
}
console.log(fillArray1(1,4)); //[ 1, 2, 3, 4 ]
console.log(fillArray1(-6,4)); // [ -6, -5, -4, -3 ]
23. Return an array between two integers of 1 step length
const fillArray = (start, end) => {
return Array.from({length: end-start+1}, (v, i)=> i+start)
}
console.log(fillArray(1,4)); //[ 1, 2, 3, 4 ]
console.log(fillArray(-6,4)); // [ -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4 ]
24. Find the unique elements from two arrays
const findUnique = (arr1, arr2) => {
arr1 = arr1.toString().split(',').map(Number);
arr2 = arr2.toString().split(',').map(Number);
console.log( [... new Set(arr1.concat(arr2))] );
}
findUnique([1, 2, 3], [100, 2, 1, 10]) // [ 1, 2, 3, 100, 10 ]
findUnique([1, 2, 3, 4, 5], [1, [2], [3, [[4]]],[5,6]])//[ 1, 2, 3, 4, 5, 6 ]
25. Create an array of arrays, ungrouping the elements in an array produced by zip
function unzip1(arr) {
let res = [];
let maxLen = Math.max(... arr.map(a => a.length))
for(let i=0; i< maxLen; i++){
res.push(arr.map(a => a[i]))
}
return res
}
console.log(unzip([['a', 1, true], ['b', 2, false]]))
// [ [ 'a', 'b' ], [ 1, 2 ], [ true, false ] ]
console.log(unzip([['a', 1, true], ['b', 2]]))
// [ [ 'a', 'b' ], [ 1, 2 ], [ true, undefined ] ]
26. Remove falsy values from object
function cleaning(input){
const data = Array.isArray(input) ? input.filter(Boolean): input;
return Object.keys(data).reduce((acc, key) =>{
const value = data[key]
if(Boolean(value)){
acc[key] = typeof value == 'object' ? cleaning(value) : value;
}
return acc
},
Array.isArray(input) ? [] : {}
);
}
const obj = {
a: null,
b: false,
c: true,
d: 0,
e: 1,
f: '',
g: 'a',
h: [null, false, '', true, 1, 'a'],
i: { j: 0, k: false, l: 'a' }
}
let arr = [1,3,''. null, false, 9, 0]
console.log(cleaning(arr)); // [ 1, 3, 9 ]
console.log(cleaning(obj));
//{ c: true, e: 1, g: 'a', h: [ true, 1, 'a' ], i: { l: 'a' } }
27. Take an array of integers and returns false if every number is not prime.
const isAllPrime = (arr) => {
const isPrime = (x) =>{
for(let i=2; i <= Math.sqrt(x); i++){
if(x%i === 0)
return false
}
return x > 1
}
return arr.map(isPrime).every(Boolean)
}
let arr = [2,3,5,7]
console.log(isAllPrime([2,3,5,7]))// true
console.log(isAllPrime([2,3,5,7,8]))// false
28. Return the third smallest number
let arr = [2,3,5,7,1]
const thirdSmallest= (arr) => arr.length > 2 ? arr.sort((a,b) => a-b)[2] : -1
console.log(thirdSmallest([2,3,5,7,1])); //3
console.log(thirdSmallest([2,3,0,5,7,8,-2,-4])); // 0
29. Return sum of all numbers in array
const sumUp = arr => arr.reduce((total, curr) => {
total = typeof curr === 'number' ? total + curr : total;
return total
}, 0)
console.log(sumUp(['',10,1,2,'3'])); // 13
console.log(sumUp([2, "11", 3, "a2", false, 5, 7, 1])); // 18
console.log(sumUp([2, 3, 0, 5, 7, 8, true, false])); // 25
30. Get all indexes where NaN is found
const indexesOfNaN = (arr) => {
let res = []
for(let [i,x] of arr.entries()){
if (isNaN(x))
res.push(i)
}
return res
}
console.log(indexesOfNaN([2, NaN, 8, 16, 32])); // [1]
console.log(indexesOfNaN([2, 4, NaN, 16, 32, NaN])); // [2,5]
console.log(indexesOfNaN([2, 4, 16, 32])); // []
31. Count of the number of arrays inside given array
let ls = [2,8,[6],3,3,5,3,4,[5,4]]
const getCountOfInternalArrays = (ls) => ls.filter(
l => Array.isArray(l)
).length
console.log(getCountOfInternalArrays(ls)); // 2
Please do let me know if you solve with a better solution, OR If you find these solutions better then let me know in the comments 💌
Â