Skip to content

Commit 59502de

Browse files
committed
added new questions related to array
1 parent b77b5af commit 59502de

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

Interview-Questions/arrObj.js

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,3 +189,62 @@ const newHeroes2 = heroes.map((hero) =>
189189
); // or return {...h, name: h.name.toUpperCase()};
190190

191191
console.log(heroes);
192+
193+
// What is the problem with sort() function? Why javascript introduced toSorted() function
194+
195+
/**
196+
* Ans: sort() function mutates the original array
197+
* toSorted() method takes an array and returns a new array with the elements sorted in ascending order. It does not mutate the original array. All undefined elements are sorted to the end of the array.
198+
* */
199+
200+
const arr = [1, 8, 6, 9, 7, 100, 400, 200];
201+
202+
const oldSortedArr = arr.sort((a, b) => a - b);
203+
204+
console.log(arr); // [1, 6, 7, 8, 9, 100, 200, 400] (mutated the original array)
205+
console.log(oldSortedArr, arr); // [1, 6, 7, 8, 9, 100, 200, 400]
206+
207+
const newSortedArr = arr.toSorted((a, b) => a - b);
208+
209+
console.log(arr); // [1, 6, 7, 8, 9, 100, 200, 400] (does not mutated the original array)
210+
console.log(newSortedArr); // [1, 6, 7, 8, 9, 100, 200, 400]
211+
212+
// Remove the duplicates item from an array without build in funcitons
213+
const arr = [4, 1, 8, 5, 2, 1, 8, 4, 7, 5, 6, 9];
214+
215+
const removeDuplicates = (arrData) => {
216+
const obj = {};
217+
for (const item of arrData) {
218+
obj[item] = item;
219+
}
220+
221+
return Object.values(obj);
222+
};
223+
224+
console.log(removeDuplicates(arr));
225+
226+
// Write a program for array intersection (keep the only common items from two arrays) (without build in functions)
227+
228+
const arr = [1, 4, 5, 6, 9];
229+
const arr1 = [2, 1, 7, 5, 9, 6];
230+
231+
const getCommonItems = (arrData, arrData1) => {
232+
const obj = {};
233+
const resArr = [];
234+
235+
for (const item of arrData) {
236+
obj[item] = item;
237+
}
238+
239+
for (const item1 of arrData1) {
240+
if (obj[item1]) resArr.push(item1);
241+
}
242+
243+
return resArr;
244+
};
245+
246+
console.log(getCommonItems(arr, arr1));
247+
248+
// Optional => using build in functions
249+
const intersectedArr = arr.filter((item) => arr1.includes(item));
250+
console.log(intersectedArr);

0 commit comments

Comments
 (0)