Guess the output
let arr1 = [1, 2, 3];
let arr2 = arr1;
arr1.push(4);
console.log("arr1", arr1);
console.log("arr2", arr1);
//Output
// arr1 (4)Â [1, 2, 3, 4]
// arr2 (4)Â [1, 2, 3, 4]
let arr5 = [1, 2, 3];
let arr6 = [...arr5];
arr6.push(4);
console.log("arr5", arr5); //[1,2,3]
console.log("arr6", arr6); //[1,2,3,4]
let arr8 = [1, 2, 3];
let arr9 = arr8.slice();
arr9.push(4);
console.log("arr8", arr8); //??
console.log("arr9", arr9); //??
Guess the output - last two console.log
HOVER TO SEE THE ANSWER
Slice() Doesn't Impact Original Array
console.log("arr8", arr8); //[1,2,3]
console.log("arr9", arr9); //[1,2,3,4]
console.log("arr9", arr9); //[1,2,3,4]
Print all the sons of this family.
//Print all the sons of this family...
let family = [
{
father: "Narasimha",
sons: ["Rohan", "Roshan"],
},
{
father: "Ganesh",
sons: ["Anurag", "Abhishek"],
},
{
father: "Rudra Prasad",
sons: ["Ritesh", "Ritika"],
},
{
father: "Rajesh Prasad",
sons: ["Lisa", "Bablu"],
},
];
let finalList = family.reduce((acc, curr) => {
return [...acc, ...curr.sons];
}, []);
//Â ['Rohan', 'Roshan', 'Anurag', 'Abhishek', 'Ritesh', 'Ritika', 'Lisa', 'Bablu']
// --> don't miss the last [] part else you will get error..
// acc is not iterable
Don't miss the last [] part inside reduce, else you will get error.. .. acc is not iterable
1 missing number between continous series of number
//find the missing number between 1 to 20
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
console.log((20 * 21) / 2 - arr.reduce((acc, curr) => acc + curr));
Sum of all consecutive numbers is – n*(n+1)/2Â – sum of all numbers in the array = The Missing Number
sort array of objects by property
//sort the array objects by title
var library = [
{ author: "Nehru", title: "The Discovery Of India" },
{ author: "Dr A.P.J Abdul Kalam", title: "Wings of fire" },
{ author: "Indira Gandhi", title: "My Truth" },
];
library.sort((a, b) => (a.title > b.title ? 1 : -1));
console.log(library);
Create blank array of size n (fill with zero)
//3 ways to create blank array of n size
const arr = Array.from(Array(10), () => 0);
console.log(arr);
const arr1 = Array.apply(null, Array(10)).map(() => 0);
console.log(arr1);
const arr2 = new Array(10).fill(0);
console.log(arr2);
var another = Array.of(0,0,0,0,0,0,0,0,0,0);
console.log(another)
//[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Shuffle Array randomly -1st way
//shuffle array
let arr = [1, 2, 3, 4, 5];
let shuffledArray = arr
.map((val) => ({ val, sort: Math.random() }))
.sort((x, y) => x.sort - y.sort)
.map(({ val }) => val);
console.log(shuffledArray);
//[3, 1, 5, 2, 4]
//[3, 2, 4, 5, 1]
Shuffle Array randomly - 2nd way
//Fisher yates shuffle
/*
currentIndex at start will be -5
randomIndex will be between - 0 till 4 ?? how ?
Math.random() --say it comes as 0.9
0.98*5 => 4.9 ..Floor will make it 4
So random Index will be always between 0 till 4
currentIndex --4 reduced
so in first iteration -
we swap here --current index(4) and randomIndex(4)
[1,2,3,4,5] --> [1,2,3,4,5]
second iteration
currentIndex-4
randomIndex will be between - 0 till 4
let us assume we get 2 again randomIndex
currentIndex --3 reduced
we swap here --current index(3) and randomIndex(2)
[1,2,3,4,5] --> [1,2,4,3,5]
third iteration
currentIndex-3
randomIndex will be between - 0 till 4
let us assume we get 1 again randomIndex
currentIndex --2 reduced
we swap here --current index(2) and randomIndex(1)
[1,2,4,3,5] --> [1,4,2,3,5]
fourth iteration
currentIndex-2
randomIndex will be between - 0 till 4
let us assume we get 0 again randomIndex
currentIndex --1 reduced
we swap here --current index(1) and randomIndex(0)
[1,4,2,3,5] --> [4,1,2,3,5]
last iteration
currentIndex-1
randomIndex will be between - 0 till 4
let us assume we get 0 again randomIndex
currentIndex --0 reduced
we swap here --current index(0) and randomIndex(0)
[4,1,2,3,5] --> [4,1,2,3,5]
*/
let shuffle = (array) => {
let currentIndex = array.length;
let randomIndex;
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
console.log(randomIndex);
currentIndex--;
[array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
}
return array;
};
console.log(shuffle([1, 2, 3, 4, 5]));
Shuffle Array randomly - 3rd way
const arr= [4,2,1,3,5]
arr.sort(()=> Math.random()-0.5);
Guess the output
const arr= [4,2,1,3,5]
arr.sort(()=> -1);
arr.sort(() => -2);
Guess the output --Hover on this to see the answer
Undefined
[5,4,3,2,1]
[1,2,3,4,5]
[1,2,3,4,5]
Empty Array
//How to empty array
var array1 = [1, 2, 3, 4];
array1 = [];
console.log("array1", array1);
var array2 = [1, 2, 3, 4];
array2.length = 0;
console.log("array2", array2);
var array3 = [1, 2, 3, 4];
while (array3.length > 0) {
array3.pop();
}
console.log("array3", array3);
var array4 = [1, 2, 3, 4];
array4.splice(0, array4.length);
console.log("array4", array4);
//output:-
// array1 []
// array2 []
// array3 []
// array4 []
Guess the output
let num = [1, 2, , 4, 5, null];
console.log(num[2]);
Guess the output --Hover on this to see the answer
Undefined
Slice vs Splice - Differences
//*******************************SPLICE*************************************************
//THE INDEX WILL BE INCLUSIVE -->
//[1,2,3,4,5]
//1. SPLICE(1,3) --> INDEX 1 AND 3 WILL BE INCLUSIVE..
//NEW ARRAY --> THE REMOVED OR SPLICED ONE --> INDEX INCLUSIVE --> [2,3,4]
//ORIGINAL ARRAY --> LEFT ONE --> [1,5]
//2. SPLICE(1,3,"X")
//[1,2,3,4,5]
//NEW ARRAY --> THE REMOVED OR SPLICED ONE --> INDEX INCLUSIVE --> [2,3,4]
//ORIGINAL ARRAY --> LEFT ONE BUT WITH UPDATED VALUE X IN BETWEEN THE REMOVED INDEX--> [1,"X",5]
let original = [1, 2, 3, 4, 5];
let newArray = original.splice(1, 3);
console.log(original); //[1,5]
console.log(newArray); //[2,3,4]
let original1 = [1, 2, 3, 4, 5];
let newArray1 = original1.splice(1, 3, "anurag");
console.log(original1); //[1,"anurag",5]
console.log(newArray1); //[2,3,4]
//*******************************SLICE****************************************************
//ORIGINAL ARRAY IS NOT AFFECTED
//NEW ARRAY -->START INDEX IS INCLUSIVE, END INDEX IS EXCLUSIVE --> [2,3]
let original2 = [1, 2, 3, 4, 5];
let newArray2 = original2.slice(1, 3);
console.log(original2); //[1,2,3,4,5]
console.log(newArray2); //[2,3]
SPLICE - BOTH INDEX INCLUSIVE
Splice --> Original array gets affected
SLICE - START INDEX INCLUSIVE, END INDEX EXCLUSIVE
Slice --> Original array doesnt get impacted...
Random question on spread operator
//This is pretty straightforward --> new array will not impact the original array
let num1 = [1, 2, 3, 4, 5];
let copyNum1 = [...num1];
copyNum1[0] = 99;
console.log("copyNum1", copyNum1); //[99, 2, 3, 4, 5]
console.log("num1", num1); //[1, 2, 3, 4, 5]
//-----------------------------------------------------------------------------------------
//But have a look at below question
//Original array gets affected ??? why ?? Array is copied but underlying objects are still accessed by reference
let products = [
{
model: "Royal Enfield Interceptor 650",
price: "2.89 lakhs",
},
{
model: "Royal Enfield Continental",
price: "3.09 lakhs",
},
{
model: "Royal Enfield Classic 350",
price: "1.52 lakhs",
},
];
let copyProduct = [...products];
copyProduct[0].model = "Royal Enfield Himalayan";
console.log(copyProduct[0].model); //Royal Enfield Himalayan
console.log(products[0].model); //Royal Enfield Himalayan
//--------------------------------------------------------------------------------------
//Here it will not impact the original object ..as we are using spread operator to copy the object
let product1 = {
model: "Royal Enfield Interceptor 650",
price: "2.89 lakhs",
};
let product2 = { ...product1 };
product2.model = "Royal Enfield Himalayan";
console.log(product2.model); //Royal Enfield Himalayan
console.log(product1.model); //Royal Enfield Interceptor 650
Spread Operator one more usage in Date()
let date1 = new Date(2022, 8, 2022);
console.log(date1); //Tue Mar 14 2028 00:00:00 GMT+0530 (India Standard Time)
let dateFields = [2022, 8, 2022];
let date2 = new Date(...dateFields);
console.log(date2); //Tue Mar 14 2028 00:00:00 GMT+0530 (India Standard Time)
Calculate Average in number array
//calculate average of the array
let numbers = [1, 2, 3, 4, 5];
//average is -->15/5 =3
//attempt1
let sum = numbers.reduce((acc, curr) => acc + curr);
console.log(sum / numbers.length);
//attempt2
let avg = numbers.reduce((acc, curr, index, arr) => {
if (arr.length === index + 1) {
return (acc + curr) / arr.length;
}
return acc + curr;
}, 0);
console.log(avg);
Assign negative index or string in array- behaves like object
let num = [1, 2, 3, 4];
num[-1] = 50;
num["name"] = "anurag";
console.log(num);
// (4) [1, 2, 3, 4, -1: 50, name: 'anurag']
// 0: 1
// 1: 2
// 2: 3
// 3: 4
// -1: 50
// name: "anurag"
// length: 4
//************Key points ***********/
//Outupt--> Array behaves like object
//you can access below num[-1] or num["name"] like object properties
//num[-1] --> 50 , num["name"] --> "anurag"
//Length is still 4 -- not 6
console.log(num[-1]); //50
console.log(num["name"]); //anurag
console.log(num.length); //4
//*********Key points ***************/
// Lets loop - using for in
// As you know we can loop objects using for in...
for (let x in num) {
console.log(`Key -->:${x} :: Value --> ${num[x]}`);
}
//output
// Key -->:0 :: Value --> 1
// Key -->:1 :: Value --> 2
// Key -->:2 :: Value --> 3
// Key -->:3 :: Value --> 4
// Key -->:-1 :: Value --> 50
// Key -->:name :: Value --> anurag
Array.from usages
let empName = "Anurag";
console.log([...empName]); //['A', 'n', 'u', 'r', 'a', 'g']
console.log(Array.from(empName)); //['A', 'n', 'u', 'r', 'a', 'g']
// ***create array of length 10 using Array.from ..fill with numbers cube****
const createNewArray1UsingFrom = Array.from({ length: 10 }, (val, index) => index * index * index);
console.log(createNewArray1UsingFrom); //[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
//using fill
const createNewArray1UsingFill = new Array(10).fill(0).map((val, index) => index * index * index);
console.log(createNewArray1UsingFill); //[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
//Remove Duplicates using Array.from
let num = [1, 2, 2, 2, 3, 4, 5];
console.log(Array.from(new Set(num))); //[1, 2, 3, 4, 5]
//COMBINE ARRAY OF CHARACTERS
let characters = ["A", "N", "U", "R", "A", "G"];
console.log(Array.from(characters).join("")); //ANURAG
Find First duplicate value occurence using Map
const num = [1, 2, 3, 4, 2, 3, 4, 6, 8];
let map = new Map();
let output = num.map((item) => {
if (map.has(item)) {
return item;
}
map.set(item);
});
//output - [undefined, undefined, undefined, undefined, 2, 3, 4, undefined, undefined]
console.log(output.find((i) => i));
Find First duplicate value occurence using Filter
const num = [1, 2, 3, 4, 2, 3, 4, 6, 8];
let map = new Map();
let output = num.filter((item) => {
if (map.has(item)) {
return item;
}
map.set(item);
});
//output - [2, 3, 4]
//This also fetches you all duplicates in the array- 2 3 4
console.log(output[0]);
Find First duplicate value occurence using Find
const num = [1, 2, 3, 4, 2, 3, 4, 6, 8];
let map = new Map();
let output = num.find((item) => {
if (map.has(item)) {
return item;
}
map.set(item);
});
//output - 2
//This fetches you 2
console.log(output);
Find First duplicate value occurence using Every
const num = [1, 2, 3, 4, 2, 3, 4, 6, 8];
let map = new Map();
let final;
let output = num.every((item) => {
if (map.has(item)) {
final = item;
return false;
}
map.set(item);
return true;
});
console.log(final);
Find First duplicate value occurence using some
const num = [1, 2, 3, 4, 2, 3, 4, 6, 8];
let map = new Map();
let final;
let output = num.some((item) => {
if (map.has(item)) {
final = item;
return true;
}
map.set(item);
});
// //output - 2
console.log(final);
Number with maximum repititions
//output shoule be - number with maximum repition
// 5 --> 5
// 5 is repeated 5 times
const number = [1, 5, 5, 5, 5, 5, 4, 4, 4, 3, 2];
let map = new Map();
let count = 0;
let max = 0;
let maxNum = 0;
number.forEach((i) => {
if (map.has(i)) {
count = map.get(i);
}
map.set(i, ++count);
if (count > max) {
max = count;
maxNum = i;
}
count = 0;
});
console.log(maxNum + " is repeated ::" + max + " times");
Maximum number in Array and its repititions
//Find the maximum value.. Find out the repition of that number
//8 is repeated 6 times
//1st solution
const dataset = [8, 8, 1, 5, 5, 5, 5, 5, 4, 4, 4, 3, 2, 8, 8, 8, 8];
let max = Math.max(...dataset); //8
var count = dataset.reduce(function (counter, value) {
return counter + (value === max);
}, 0);
//2nd solution
let max1 = Math.max(...dataset); //8
let count = dataset.filter(x => x === max1).length;
console.log(max1 + " is repeated ::" + count + " times");
Remove duplicate nested array
let foodItems = [
["Chicken Tikka", "Paneer Masala"],
["Chicken Tikka", "Mix Veg"],
["Paneer Masala"],
];
//output should be
//[Chicken Tikka , Paneer Masala , Mix Veg]
let final = [...new Set(foodItems.flat())];
console.log(final);
Combine two different array
//Expected output
//[1,"one",2,"two",3,"three"]
const nums = [1, 2, 3];
const strs = ["one", "two", "three"];
const mapped = nums.map((val, index) => [val, strs[index]]);
console.log(mapped.flat(1));
const mapped1 = nums.flatMap((val, index) => [val, strs[index]]);
console.log(mapped1);
reduceRight
const myReverseName = ["g", "a", "r", "u", "n", "a"];
let final = myReverseName.reduceRight((c, v) => c + v);
console.log(final);
//output :- anurag
Sum of age of all family members
const familyTree = [
{
name: "Anurag",
age: 82,
children: [
{
name: "Rahul",
age: 53,
children: [
{
name: "Vinay",
age: 32,
},
{
name: "Priya",
age: 28,
children: [
{
name: "Srinivas",
age: 5,
},
],
},
],
},
{
name: "Roshan",
age: 50,
},
],
},
{
name: "Abhishek",
age: 50,
children: [],
},
];
//sum of all age --> 82 + 53 + 32 + 28 + 5 + 50 + 50 =300
let sum = 0;
const calculateSumOfAge = (family) => {
if (Array.isArray(family)) {
family.forEach((i) => {
sum += i.age;
if (i.children) {
calculateSumOfAge(i.children);
}
});
}
};
calculateSumOfAge(familyTree);
console.log(sum);
//output:300
Merge and Sort Number Array
//Merge and sort
const x = [1, 5, 2, 5, 8, 3];
const y = [6, 1, 2, 9, 4, 6, 3];
let final = [...x, ...y].sort((a, b) => a - b);
console.log(final);
//[1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 8, 9]
Chunked Array
//CHUNKED ARRAY
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
//n=3
//output should be
//[[1,2,3],[4,5,6],[7,8,9]]
//n=4
//output should be
//[[1,2,3,4],[5,6,7,8],[9]]
//n=7
//output should be
//[[1,2,3,4,5,6,7],[8,9]]
//n=10 or n=9
//[1,2,3,4,5,6,7,8,9]
let finalArray = [];
const chunkArray = (arr, n) => {
if (n >= arr.length) {
finalArray = arr;
return arr;
}
while (arr.length !== 0) {
let chunkedArray = arr.splice(0, n);
finalArray.push(chunkedArray);
}
};
chunkArray(arr, 9);
chunkArray(arr, 3);
chunkArray(arr, 4);
console.log(finalArray);
//Explanation if n is 3
//[1,2,3,4,5,6,7,8,9]
//splice(0,3)
//splice includes both start and last index
//[1,2,3] - this will be pushed to finalArray
//In Splice - orginal array gets affected.. so we are left with [3,4,5,6,7,8,9]
//Now the loop continues till the length becomes zero
for (of vs in)
for in -->
property
picks the index {0:"Rohit", 1:"Virat", 2: "Bumrah"];
for of -->
value
picks the index {0:"Rohit", 1:"Virat", 2: "Bumrah"];
const cricketers = ["Rohit", "Virat", "Bumrah"];
//Array is actually object
{
0:"Rohit",
1:"Virat",
2:"Bumrah"
}
//INDEX IS PICKED - for in
for (let name in cricketers) {
console.log(name);
}
//!OUTPUT -0 1 2
//VALUE IS PICKED - for of
for (let name of cricketers) {
console.log(name);
}
//!OUTPUT -Rohit Virat Bumrah
.every (To verify if all elements in array satisfies the condition)
//Every is like all in c# - It returns value - true or false
//inline you can write or you can invoke separate function..
const ages = [10, 20, 30, 23];
const checkAge = (age) => {
return age > 18;
};
//1st way
console.log(ages.every(checkAge));
//2nd way
console.log(
ages.every((age) => {
return age > 18;
})
);
//output for both - false
Fetch value from nested array
const nestedArray = [[["I am here"]]];
//Level is only 3 - so it is fine to fetch like this
//but if the level increases then we need to opt
//for other option
nestedArray.forEach((array1) => {
array1.forEach((array2) => {
array2.forEach((element) => {
console.log(element);
});
});
});
//Fetch Recursively
//Even this might have glitch if level is too deep
//You can flatten and fetch - Kindly follow below examples
const retrieveRecursively = (element) => {
if (Array.isArray(element)) {
return retrieveRecursively(element[0]);
} else return element;
};
console.log(retrieveRecursively(nestedArray));
Flatten Array and Sum
/////EXPLANATION OF FLATTENING///////
//[1, 2, [3, 4], 5, 6, [7, 8, 9]];
//1,2,[3,4],5,6,[7,8,9] --> Total input length -->6
//input.shift() -->removes first element...1 is removed
//1 is not array --> pushed to result
//2 is not array --> pushed to result ..2 is removed from input
//[3,4] is removed from input ...it is array
//[3,4] is flattened --> It is pushed to input not result
//now input is [5,6,[7,8,9],3,4]
//now 5 is straight forward not array -->pushed to result..removed from input
//now 6 is straight forward not array -->pushed to result..removed from input
//result is [1,2,5,6]
//now input is [[7,8,9],3,4]
//now [7,8,9] is flattened and pushed to input at the end
//now input is [3,4,7,8,9]
//now result is pushed with above value [1,2,5,6] + [3,4,7,8,9]
//input is empty at the end ..while loop ends
//final output ==> [1,2,5,6,3,4,7,8,9]
////////////////////////QUESTION////////////////
let input = [1, 2, [3, 4], 5, 6, [7, 8, 9]];
//expected output - sum of all elements in above array
// 1+2+3+4+5+6+7+8+9 = 45
const flatten = (input) => {
let result = [];
while (input.length) {
let next = input.shift();
if (Array.isArray(next)) {
input.push(...next);
} else {
result.push(next);
}
}
return result;
};
let flattenedArray = flatten(input);
let sum = flattenedArray.reduce((acc, curr) => acc + curr, 0);
console.log(flattenedArray); //[1,2,5,6,3,4,7,8,9]
console.log(sum); //45
Flatten Array -2nd way
var nestedArray = [[[[1, 2, 3]]], [4], [5, 6, 7], [[8, 9]]];
const flattenArray = (items) => {
const flat = [];
for (let i = 0; i < items.length; i++) {
const element = items[i];
if (Array.isArray(element)) {
const flatItem = flattenArray(element);
for (let j = 0; j < flatItem.length; j++) {
flat.push(flatItem[j]);
}
} else {
flat.push(element);
}
}
return flat;
};
console.log(flattenArray(nestedArray));
Flatten Array -3rd way - Just improvement of 2nd way - spread operator is used
//Flatten it as [1,2,3,4,5,6,7,8,9]
//Explanation
//first it breaks into 4 items
//[[[1, 2, 3]]] -->[4] -->[5, 6, 7] -->[[8, 9]]
//Recursion runs on [[[1, 2, 3]]] till it goes and adds in else block 1,2,3
//Then it pushes to flat.push(...flattenArray(item));
//Recursion runs on [4] till it goes and adds in else block 4.
//here flat array will have only one item --> 4 in else block
//Then it pushes to flat.push(...flattenArray(item)); --existing 1,2,3 + now 4 from above statement
//Recursion runs on [5, 6, 7] till it goes and adds in else block 4.
//here flat array will have only 3 items --> 5,6,7 in else block
//Then it pushes to flat.push(...flattenArray(item));
//--existing 1,2,3,4 + now 5,6,7 from above statement
//Recursion runs on [7, 8, 9] till it goes and adds in else block 4.
//here flat array will have only 3 items --> 7,8,9 in else block
//Then it pushes to flat.push(...flattenArray(item));
//--existing 1,2,3,4,5,6 + now 7,8,9 from above statement
//--> Final Array ==> [1,2,3,4,5,6,7,8,9]
var nestedArray = [[[[1, 2, 3]]], [4], [5, 6, 7], [[8, 9]]];
const flattenArray = (items) => {
const flat = [];
items.forEach((item) => {
if (Array.isArray(item)) {
flat.push(...flattenArray(item));
console.log(flat);
} else {
flat.push(item);
}
});
return flat;
};
console.log(flattenArray(nestedArray));
TIME COMPLEXITY - O(N)
SPACE COMPLEXITY - O(N)
SPACE COMPLEXITY - O(N)
Find the maximum in array
The recommended one is to use
reduce or loop
As for larger arrays Math.Max gives max stack overflow exception
let array = [10, 20, 50, 15, 12];
//*******1***********
let max = array.reduce((max, curr) => {
if (curr > max) {
max = curr;
}
return max;
});
//*******2***********
let max_of_array1 = Math.max.apply(Math, array);
//*******3***********
let max_of_array2 = Math.max(...array);
//*******Outuput**********
console.log(max_of_array1);
console.log(max_of_array2);
console.log(max);
OUTPUT- 50
fetch values except (undefined,null,"",false,0)
let inputArray = [1, false, 0, undefined, "", "test", null, 25, -25, 25.6];
//it will exclude 0 false undefined null
console.log(inputArray.filter(Boolean));
//[1, 'test', 25, -25, 25.6]
0 is included
let inputArray1 = [1, false, 0, "test", undefined, "", null, 25, -25, 25.6];
//Included zero as well
console.log(inputArray1.filter((x) => Boolean(x) || x === 0));
//[1, 0, "test", 25, -25, 25.6];
0 is included, filtered string value
let inputArray2 = [1, false, 0, "test", undefined, "", null, 25, -25, 25.6];
//Included zero ,filtered 'test'
console.log(inputArray2.filter((x) => (!isNaN(x) && Boolean(x)) || x === 0));
//[1, 0, 25, -25, 25.6]
Maximum frequently occuring string inside an array
const arr = ["abc", "a", "abc", "abc", "b", "b", "abc"];
//most frequent string inside array
const mostFrequentString = (arr) => {
let map = new Map();
let maxStringValue = { key: arr[0], value: 1 };
for (let element of arr) {
if (map.has(element)) {
let currentValue = map.get(element) + 1;
if (currentValue > maxStringValue.value) {
maxStringValue.value = currentValue;
maxStringValue.key = element;
}
map.set(element, currentValue);
} else {
map.set(element, 1);
}
}
return `${maxStringValue.key} repeated --> ${maxStringValue.value} times`;
};
console.log(mostFrequentString(arr));
/*
Explanation
1. you cannot use set to keep key value
2. using map to store key and value -let map = new Map();
3. keeping track of object - the final output - key repeated x times
a) let maxStringValue = { key: arr[0], value: 1 }; -- storing first item of array
b) you can check for length - if no items return -- I haven't done that
4. for of - is used to loop over the values in array
5. Don't use for in - it will be index - 0 ,1 ,2....
6. First time string - you just set the map to -key as the element , value --> 1
6. If you encounter same string
a) increment the map ..key as the same element , value -> prev value + 1
b) store the maxStringValue as well to keep track of the maximum repeated string and its value
c) Keep changing the maxStringValue - if the currentValue is more than maxStringValue.value
7.After you exit the loop just print the maxStringValue.key and maxStringValue.value
*/
flat to nested array
const flatArray = [
{
id: 1,
name: "Suresh",
parentId: null,
},
{
id: 2,
name: "Ganesh",
parentId: 1,
},
{
id: 3,
name: "Roshan",
parentId: null,
},
{
id: 4,
name: "Rohan",
parentId: 3,
},
{
id: 5,
name: "Ritesh",
parentId: 4,
},
];
/*
-->Expected output
[
{
id:1,
children:[
{
id:2,
children:[]
}
]
},
{
id:3,
children:[
{
id:4,
children:[
{
id:5,
children:[]
}
]
}
]
},
]
*/
const mapChildren = (item) => {
const children = flatArray.filter((childItem) => childItem.parentId === item.id);
let nestedChildren = [];
if (children.length > 0) {
nestedChildren = children.map((child) => mapChildren(child));
}
return Object.assign({}, item, { children: nestedChildren });
};
const finalOutput = flatArray.filter((i) => i.parentId === null).map(mapChildren);
console.log(finalOutput);