JavaScript : Interview Questions

(1) Cloning an Object in Javascript: Shallow Copy vs. Deep Copy
In JavaScript, when you want to duplicate an object or an array, you can create either a shallow copy or a deep copy. The difference between the two lies in how nested objects and arrays are copied. Let’s explore both concepts:
Shallow Copy:
- A shallow copy duplicates the outermost object or array and its immediate elements, but it does not create copies of the nested objects or arrays within the original structure.
- If you modify the nested objects or arrays in the copy, these changes will be reflected in the original structure, and vice versa.
- Shallow copies can be created using various methods, including
Object.assign()
, the spread operator (...
), and theArray.slice()
method.
// Example of a shallow copy using the spread operator:
const originalArray = [1, 2, {a: 3}];
const shallowCopy = [...originalArray];
shallowCopy[2].a = 42; // Modifies the nested object in both arrays
console.log(originalArray[2].a); // Outputs 42
Deep Copy:
- A deep copy duplicates the outermost object or array as well as all the nested objects and arrays, creating a completely independent copy.
- Changes made to the deep copy do not affect the original structure, and vice versa.
- Creating a deep copy in JavaScript can be more complex, especially if your object or array has nested structures. Common methods to achieve deep copy include using recursion, libraries like Lodash, or the structured cloning algorithm for certain objects in modern JavaScript environments.
// Example of a deep copy using Lodash:
const _ = require('lodash'); // Import the Lodash library
const originalObject = {a: 1, b: {c: 2}};
const deepCopy = _.cloneDeep(originalObject);
deepCopy.b.c = 42; // Modifies the nested object only in the deep copy
console.log(originalObject.b.c); // Outputs 2
(2) Flatten an Array/Object
In JavaScript, you can flatten an array or an object to a single level using recursive or iterative approaches, depending on your input structure. Here are examples for both scenarios:
Flatten an Array :
- Using Recursive Function :
function flattenArray(arr) {
let result = [];
arr.forEach((item) => {
if (Array.isArray(item)) {
result = result.concat(flattenArray(item));
} else {
result.push(item);
}
});
return result;
}
const nestedArray = [1, 2, [3, 4, [5, 6]], 7];
const flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray);
2. Using Array.prototype.flat (ES6+) :
const nestedArray = [1, 2, [3, 4, [5, 6]], 7];
const flattenedArray = nestedArray.flat(Infinity);
console.log(flattenedArray);
Flatten an Object:
Using Recursive Function :
function flattenObject(obj) {
let result = {};
for (let key in obj) {
if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
const temp = flattenObject(obj[key]);
for (let nestedKey in temp) {
result[`${key}.${nestedKey}`] = temp[nestedKey];
}
} else {
result[key] = obj[key];
}
}
return result;
}
const nestedObject = {
a: 1,
b: {
c: 2,
d: {
e: 3,
f: 4,
},
},
g: 5,
};
const flattenedObject = flattenObject(nestedObject);
console.log(flattenedObject);
Please note that the recursive approach can handle nested structures of arbitrary depth. The examples above should help you flatten arrays and objects in JavaScript.