JavaScript : Interview Coding Questions & Concepts

Utkarsh Katiyar
3 min readJun 25, 2024

1. Flatten

Flatten an array (using Flat method)

const arr = [1, [2, [3, [4, [5]]]]];
const flattened = arr.flat(Infinity);
console.log(flattened); // Output: [1, 2, 3, 4, 5]

Flatten an array (without using Flat method — using Recursion)

function flattenArray(arr) {
return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []);
}

const arr = [1, [2, [3, [4, [5]]]]];
const flattened = flattenArray(arr);
console.log(flattened); // Output: [1, 2, 3, 4, 5]

Flatten an object

function flattenObject(obj, parentKey = '', result = {}) {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
const newKey = parentKey ? `${parentKey}.${key}` : key;
if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
flattenObject(obj[key], newKey, result);
} else {
result[newKey] = obj[key];
}
}
}
return result;
}

const nestedObject = {
a: {
b: {
c: 1
},
d: 2
},
e: 3,
f: {
g: 4
}
};

const flattenedObject = flattenObject(nestedObject);
console.log(flattenedObject);
// Output: { 'a.b.c': 1, 'a.d': 2, 'e': 3, 'f.g': 4 }

2. Deep Copy & Shallow Copy

Shallow Copy

A shallow copy means that only the first level of the object or array is copied, and nested objects or arrays are still referenced by their original references.

Here’s an example using Object.assign() for objects and the spread operator for arrays:

Shallow Copy of an Object

let originalObject = {
name: "Alice",
details: {
age: 25,
address: "123 Main St"
}
};

// Shallow copy using Object.assign()
let shallowCopy = Object.assign({}, originalObject);

// Alternatively, using the spread operator
let shallowCopy2 = { ...originalObject };

// Modifying the nested object in the shallow copy
shallowCopy.details.age = 30;

console.log(originalObject.details.age); // 30
console.log(shallowCopy.details.age); // 30

Shallow Copy of an Array

let originalArray = [1, 2, 3, { a: 4, b: 5 }];

// Shallow copy using the spread operator
let shallowArrayCopy = [...originalArray];

// Modifying the nested object in the shallow copy
shallowArrayCopy[3].a = 10;

console.log(originalArray[3].a); // 10
console.log(shallowArrayCopy[3].a); // 10

In both examples, changes to nested objects or arrays in the shallow copy affect the original, because only the reference to the nested object or array is copied.

Deep Copy

A deep copy means that all levels of the object or array are copied, resulting in a completely independent clone. This can be achieved using libraries like lodash or via recursion. A common approach is using JSON.parse(JSON.stringify()), though this has limitations (e.g., it doesn't handle functions or undefined).

let originalObject = {
name: "Alice",
details: {
age: 25,
address: "123 Main St"
}
};

let originalArray = [1, 2, 3, { a: 4, b: 5 }];

// Deep copy using JSON methods
let deepCopyObject = JSON.parse(JSON.stringify(originalObject));
let deepCopyArray = JSON.parse(JSON.stringify(originalArray));

// Modifying the nested object in the deep copy
deepCopyObject.details.age = 30;
deepCopyArray[3].a = 10;

console.log(originalObject.details.age); // 25
console.log(deepCopyObject.details.age); // 30

console.log(originalArray[3].a); // 4
console.log(deepCopyArray[3].a); // 10

Using Lodash for Deep Copy

// First, include Lodash in your project
// npm install lodash

const _ = require('lodash');

let originalObject = {
name: "Alice",
details: {
age: 25,
address: "123 Main St"
}
};

let originalArray = [1, 2, 3, { a: 4, b: 5 }];

// Deep copy using lodash
let deepCopyObjectLodash = _.cloneDeep(originalObject);
let deepCopyArrayLodash = _.cloneDeep(originalArray);

// Modifying the nested object in the deep copy
deepCopyObjectLodash.details.age = 30;
deepCopyArrayLodash[3].a = 10;

console.log(originalObject.details.age); // 25
console.log(deepCopyObjectLodash.details.age); // 30

console.log(originalArray[3].a); // 4
console.log(deepCopyArrayLodash[3].a); // 10

Summary

  • Shallow Copy: Copies only the first level of the object or array. Nested objects or arrays are still referenced by their original references.
  • Deep Copy: Creates a completely independent copy of all levels of the object or array, with no shared references.

3. Frequency of array values

function getFrequency(array) {
let frequency = new Map();

array.forEach(value => {
if (frequency.has(value)) {
frequency.set(value, frequency.get(value) + 1);
} else {
frequency.set(value, 1);
}
});

return frequency;
}

// Example usage with numbers and strings
let arr = [1, "apple", 2, "banana", 2, "apple", 3, "orange", 3, 3, 4, 4, "banana", "banana"];
let freq = getFrequency(arr);
console.log(Object.fromEntries(freq));
// Output: { '1': 1, '2': 2, '3': 3, '4': 2, 'apple': 2, 'banana': 3, 'orange': 1 }

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Utkarsh Katiyar
Utkarsh Katiyar

Written by Utkarsh Katiyar

Frontend Engineer (ReactJS, NextJS) | 5+ Years of Experience | BITS - Pilani

No responses yet

Write a response