For dedicated programmers looking to learn javascript. All the the core concepts of JavaScript can be found here with coding challenges to solidify your knowledge.
Best of luck on your coding journey ; )
Write a function that takes two objects and returns a new object with combined key-value pairs. If both objects contain the same key, the value from the second object should overwrite the value in the first object.
Given two objects:
const obj1 = { a: 1, b: 2, c: 3 };
const obj2 = { b: 2, c: 4, d: 5 };The merged output should be:
{ a: 1, b: 2, c: 4, d: 5 }function mergeObjects(obj1, obj2) {
for (let key in obj2) {
obj1[key] = obj2[key];
}
return obj1;
}
const mergedResult1 = mergeObjects(obj1, obj2);
console.log(mergedResult1); // Output: { a: 1, b: 2, c: 4, d: 5 }function mergeObjects1(obj1, obj2) {
return { ...obj1, ...obj2 };
}
const mergedResult2 = mergeObjects1(obj1, obj2);
console.log(mergedResult2); // Output: { a: 1, b: 2, c: 4, d: 5 }function mergeObjects3(obj1, obj2) {
return Object.assign({}, obj1, obj2)
}
// console.log(mergeObjects3(obj1, obj2)); // Output: { a: 1, b: 2, c: 4, d: 5 }Convert an array of objects, where each object contains an id and name property, into an object where each key is an id from the original array, and the corresponding value is an object with the name property.
Input
let arr1 = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];Output
{ 1: { name: 'A' }, 2: { name: 'B' } }function transformArrayOfObject(arr) {
let obj = {};
for (const element of arr) {
obj[element.id] = { name: element.name };
}
return obj;
}
console.log(transformArrayOfObject(arr1));
// Output: { 1: { name: 'A' }, 2: { name: 'B' } }function transformArrayOfObject1(arr) {
return arr.reduce((acc, item) => {
acc[item.id] = { name: item.name };
return acc;
}, {});
}
console.log(transformArrayOfObject1(arr1));
// Output: { 1: { name: 'A' }, 2: { name: 'B' }Convert an array of strings, such as ["apple", "banana", "cherry"], into an object where each string becomes a key, and each key has a default value of 0.
Input
let arr2 = ["apple", "banana", "cherry"];Output
{ "apple": 0, "banana": 0, "cherry": 0 }function arrayToObject(arr) {
let res = {};
for (const element of arr) {
res[element] = 0;
}
return res;
}
console.log(arrayToObject(arr2));
// Output: { "apple": 0, "banana": 0, "cherry": 0 }function arrayToObject1(arr) {
return arr.reduce((acc, item) => {
acc[item] = 0;
return acc;
}, {});
}
console.log(arrayToObject1(arr2));
// Output: { "apple": 0, "banana": 0, "cherry": 0 }Write a function to take an array of numbers and return an array of squared values..
Input
let arr3= [1,2,3,4,5];Output
[ 1, 4, 9, 16, 25 ]function arrayMap(arr) {
return arr.map((data) => {
return data * data;
});
}
console.log(arrayMap(arr3));
// Output: [1, 4, 9, 16, 25]Given an array of students, group them by their city.
Input
let arr4 = [
{ name: 'A', age: 20, city: 'BLR' },
{ name: 'B', age: 20, city: 'DEL' },
{ name: 'C', age: 21, city: 'BLR' }
];Output
{
"BLR": [{ name: 'A', age: 20 }, { name: 'C', age: 21 }],
"DEL": [{ name: 'B', age: 20 }]
}function groupByCategory(arr, property) {
return arr.reduce((acc, item) => {
if (!acc[item[property]]) {
acc[item[property]] = [];
}
acc[item[property]].push({ name: item.name, age: item.age });
return acc;
}, {});
}
console.log(groupByCategory(arr4, 'city'));
// Output: { "BLR": [{ name: 'A', age: 20 }, { name: 'C', age: 21 }], "DEL": [{ name: 'B', age: 20 }] }Write a function to identify duplicates in an array and return them as a new array.
Input
let arr5= [1,2,3,1,3,4,2,5];Output
[ 1, 2, 3 ]function findDuplicate(arr){
let res=[];
for(let i=0; i<arr.length; i++){
for(let j=i+1; j<arr.length; j++){
if(arr[i]===arr[j]){
res.push(arr[i]);
}
}
}
return res;
}
console.log( findDuplicate(arr5));function findDuplicate1(arr){
let res= {}
arr.forEach(element => {
if(!res[element]){
res[element]= 1;
}
else{
res[element]= res[element]+1;
}
});
return res;
}Write a function to count the frequency of each element in an array and return an object:
Input
let arr = [1, 2, 2, 3, 3, 3, 4];Output
{ '1': 1, '2': 2, '3': 3, '4': 1 }function countFrequency(arr) {
let frequencyMap = {};
for (let element of arr) {
if (frequencyMap[element]) {
frequencyMap[element]++;
} else {
frequencyMap[element] = 1;
}
}
return frequencyMap;
}
let arr = [1, 2, 2, 3, 3, 3, 4];
console.log(countFrequency(arr)); Write a function to find and return the first occurrence of the longest string in an array of strings.
Input
const strings = ["apple", "banana", "cherry", "orange", "grape"];Output
"banana"function findFirstLongestStr(arr) {
let longest = "";
for (let data of arr) {
if (data.length > longest.length) {
longest = data;
}
}
return longest;
}function findLongestStr(arr){
return arr.reduce((acc, data)=>{
if(data.length>acc.length){
return data;
}
else{
return acc;
}
}, "")
}Given two objects:
const str = "Bittu bittu"Output
4 // ('i', 'u', 'i', 'u')function countVowels(str) {
let count = 0;
for (let char of str) {
if ("aeiou".includes(char.toLowerCase())) {
count++;
}
}
return count;
}
console.log(countVowels(str)); // Output: 4function countVowels(str) {
return str.split("").reduce((count, char) => {
if ("aeiou".includes(char.toLowerCase())) {
count++;
}
return count;
}, 0);
}
console.log(countVowels(str)); // Output: 4We can solve this in different way ( for..of, reduce, flat, flatMap)
let arr = [1, [2, [3, 4, 5]]]Output
[1, 2, 3, 4, 5]function flattenArr(arr) {
let res = []
for (let data of arr) {
if (Array.isArray(data)) {
let flatData = flattenArr(data)
res.push(...flatData)
} else {
res.push(data)
}
}
return res
}
console.log(flattenArr(arr)) // [1, 2, 3, 4, 5]function flattenArr(arr){
return arr.reduce((acc, data)=>{
if(Array.isArray(data)){
return acc.concat(flattenArr(data));
}
else{
return acc.concat(data)
}
}, [])
}
console.log(flattenArr(arr)) // [1, 2, 3, 4, 5]console.log(arr.flat(Infinity)) // [1, 2, 3, 4, 5]Write a function that merges two arrays into one, ensuring there are no duplicate values.
mergeArrays([1, 2, 3], [2, 3, 4])should return
[1, 2, 3, 4]let arr1= [1,2,3];
let arr2= [2,3,4];
function mergeArrays(arr1, arr2){
return [...new Set(arr1.concat(arr2))]
}
console.log(mergeArrays(arr1, arr2))Input
{ a: 1, b: 2, c: 3 }, Keys to remove: ['b', 'c']Output
{ a: 1 }function keysToRemove(obj, keys) {
return Object.keys(obj).reduce((res, key) => {
if (!keys.includes(key)) {
res[key] = obj[key];
}
return res;
}, {});
}
let obj = { a: 1, b: 2, c: 3 };
let keys = ['b', 'c'];
console.log(keysToRemove(obj, keys)); // { a: 1 }function keysToRemove(obj, keys) {
const res = {};
for (const key in obj) {
if (!keys.includes(key)) {
res[key] = obj[key];
}
}
return res;
}
let obj = { a: 1, b: 2, c: 3 };
let keys = ['b', 'c'];
console.log(keysToRemove(obj, keys)); // { a: 1 } isAnagram('listen', 'silent') Should return truefunction anagramChecker(str1, str2) {
if (str1.length !== str2.length) {
return false;
}
const formatStr = str => str.toLowerCase().split("").sort().join("");
return formatStr(str1) === formatStr(str2);
}
console.log(anagramChecker('listen', 'silent')) // true14. Find the missing number in an array containing n−1 integers, where the numbers are in the range 1 to n.
[1, 2, 4, 5]Should return
3function findMissing(arr){
arr.sort((a, b) => a - b);
for(let i=0;i<arr.length; i++){
if(arr[i]!==i+1){
return i+1;
}
}
return arr.length + 1;
}
let arr= [1,2,4,5];
let arr1= [1,2,3,4,5]
console.log(findMissing(arr)) // 3
console.log(findMissing(arr1)) // 6we can get sum of all number in that range (1 to max) and then get sum of input array- total sum - array sum
15. Majority Element- Find the element that appears more than n/2 times in an array. If no such element exists, return null.
.
[3, 3, 4, 2, 3, 3] should return 3
As n= arr.length= 6, element count should be greater than n/2
First will find all numbers count using hashmap, then will check whose count is greater than n/2let arr = [3, 3, 4, 2, 3, 3]
function findMajorityElement(array) {
let majorityThreshold = array.length / 2
let count = array.reduce((acc, ele) => {
acc[ele] = (acc[ele] || 0) + 1
return acc
}, {})
for (let element in count) {
if (count[element] > majorityThreshold) {
return parseInt(element)
}
}
return null
}
console.log(findMajorityElement(arr)) // 3