5 | /*
6 | #animatedElem {
7 | position: absolute;
8 | width: 20px;
9 | height: 20px;
10 | background: #ff6600;
11 | }
12 | */
13 |
14 |
15 | var elem = document.getElementById("animatedElem"),
16 | left = 0,
17 | lastFrame = +new Date,
18 | timer;
19 | // Move the element on the right at ~600px/s
20 | timer = setInterval(function() {
21 | var now = +new Date,
22 | deltaT = now - lastFrame;
23 | elem.style.left = ( left += 10 * deltaT / 16 ) + "px";
24 | lastFrame = now;
25 | // clear the timer at 400px to stop the animation
26 | if ( left > 400 ) {
27 | clearInterval( timer );
28 | }
29 | }, 16);
30 |
--------------------------------------------------------------------------------
/problems/flattenObject.js:
--------------------------------------------------------------------------------
1 | let obj = {
2 | "a": {
3 | "b": {
4 | "c": 12,
5 | "d": "Hello World",
6 | "e": null
7 | },
8 | "f": [1,2,3]
9 | }
10 | };
11 |
12 | const flatten = (obj, parentkey) => {
13 | return Object.keys(obj).reduce((acc, key) => {
14 | if (Object.prototype.hasOwnProperty.call(obj, key)) {
15 | let val = obj[key];
16 | if (typeof val === "object" && !Array.isArray(val) && val != null) { // != will catch undefined or null
17 | let flat = flatten(val, key);
18 | if (parentkey) {
19 | for (let i in flat) {
20 | let k = `${parentkey}/${i}`;
21 | acc[k] = flat[i];
22 | }
23 | } else {
24 | acc = flat;
25 | }
26 | } else {
27 | let prop = parentkey ? `${parentkey}/${key}` : key;
28 | acc[prop] = val;
29 | }
30 | }
31 | return acc;
32 | }, {});
33 | };
34 |
35 |
36 | console.log(flatten(obj));
37 |
38 | // {
39 | // a/b/c: 12,
40 | // a/b/d: "Hello World",
41 | // a/b/e: null,
42 | // a/f: [1, 2, 3]
43 | // }
44 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Pradeep Kumar
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/problems/stringPermutations.js:
--------------------------------------------------------------------------------
1 | const strPermutations = str => {
2 | if (str.length < 2) {
3 | return str; // This is our break condition
4 | }
5 |
6 | let permutations = []; // This array will hold our permutations
7 |
8 | for (let i = 0, len = str.length; i < len; i++) {
9 | let char = str[i];
10 | let remainingString = `${str.slice(0,i)}${str.slice(i+1)}`;
11 | for (let subPermutation of strPermutations(remainingString)) {
12 | permutations.push(char + subPermutation);
13 | }
14 | }
15 | return permutations;
16 | }
17 |
18 | console.log(strPermutations("abcd"));
19 | // ["abcd", "abdc", "acbd", "acdb", "adbc", "adcb", "bacd", "badc", "bcad", "bcda", "bdac", "bdca", "cabd",
20 | // "cadb", "cbad", "cbda", "cdab", "cdba", "dabc", "dacb", "dbac", "dbca", "dcab", "dcba"]
21 |
22 | // Permuation of an array
23 |
24 | function permutation(input) {
25 | let outputs = [[input[0]]];
26 | for (let i = 1; i < input.length; i++) {
27 | let current = [];
28 | for (let j = 0; j < outputs.length; j++) {
29 | let base = outputs[j];
30 | for (let k = 0; k <= base.length; k++) {
31 | let temp = base.slice();
32 | temp.splice(k, 0, input[i]);
33 | current.push(temp);
34 | }
35 | }
36 | outputs = current;
37 | }
38 | return outputs;
39 | }
40 |
41 | console.log(permutation(["a", "b", "c", "d"]));
42 | //[["d", "c", "b", "a"], ["c", "d", "b", "a"], ["c", "b", "d", "a"], ["c", "b", "a", "d"], ["d", "b", "c", "a"],
43 | // ["b", "d", "c", "a"], ["b", "c", "d", "a"], ["b", "c", "a", "d"], ["d", "b", "a", "c"], ["b", "d", "a", "c"],
44 | // ["b", "a", "d", "c"], ["b", "a", "c", "d"], ["d", "c", "a", "b"], ["c", "d", "a", "b"], ["c", "a", "d", "b"],
45 | // ["c", "a", "b", "d"], ["d", "a", "c", "b"], ["a", "d", "c", "b"], ["a", "c", "d", "b"], ["a", "c", "b", "d"],
46 | // ["d", "a", "b", "c"], ["a", "d", "b", "c"], ["a", "b", "d", "c"], ["a", "b", "c", "d"]]
47 |
--------------------------------------------------------------------------------
/problems/graph.js:
--------------------------------------------------------------------------------
1 | class Graph {
2 | constructor() {
3 | this.vertices = [];
4 | this.edges = {};
5 | this.numberOfEdges = 0;
6 | }
7 |
8 | addVertex(vertex) {
9 | this.vertices.push(vertex);
10 | this.edges[vertex] = [];
11 | }
12 |
13 | addEdge(vertex1, vertex2) {
14 | this.edges[vertex1].push(vertex2);
15 | this.edges[vertex2].push(vertex1);
16 | this.numberOfEdges++;
17 | }
18 |
19 | removeVertex(vertex) {
20 | const index = this.vertices.indexOf(vertex);
21 | if(~index) {
22 | this.vertices.splice(index, 1);
23 | }
24 | while(this.edges[vertex].length) {
25 | const adjacentVertex = this.edges[vertex].pop();
26 | this.removeEdge(adjacentVertex, vertex);
27 | }
28 | }
29 |
30 | removeEdge(vertex1, vertex2) {
31 | const index1 = this.edges[vertex1] ? this.edges[vertex1].indexOf(vertex2) : -1;
32 | const index2 = this.edges[vertex2] ? this.edges[vertex2].indexOf(vertex1) : -1;
33 | if(~index1) {
34 | this.edges[vertex1].splice(index1, 1);
35 | this.numberOfEdges--;
36 | }
37 | if(~index2) {
38 | this.edges[vertex2].splice(index2, 1);
39 | }
40 | }
41 |
42 | size() {
43 | return this.vertices.length;
44 | }
45 |
46 | relations() {
47 | return this.numberOfEdges;
48 | }
49 |
50 | traverseDFS(vertex, fn) {
51 | if(!~this.vertices.indexOf(vertex)) {
52 | return console.log('Vertex not found');
53 | }
54 | const visited = {};
55 | this._traverseDFS(vertex, visited, fn);
56 | }
57 |
58 | _traverseDFS(vertex, visited, fn) {
59 | visited[vertex] = true;
60 | if (typeof fn === "function") {
61 | fn(vertex);
62 | }
63 | this.edges[vertex].forEach(adjVertex => {
64 | if(!visited[adjVertex]) {
65 | this._traverseDFS(adjVertex, visited, fn);
66 | }
67 | });
68 | }
69 |
70 | traverseBFS(vertex, fn) {
71 | if(!~this.vertices.indexOf(vertex)) {
72 | return console.log('Vertex not found');
73 | }
74 | const queue = [vertex];
75 | const visited = {[vertex] : true};
76 |
77 | while(queue.length) {
78 | vertex = queue.shift();
79 | if (typeof fn === "function") {
80 | fn(vertex);
81 | }
82 | this.edges[vertex].forEach(vEdge => {
83 | if(!visited[vEdge]) {
84 | visited[vEdge] = true;
85 | queue.push(vEdge);
86 | }
87 | });
88 | }
89 | }
90 |
91 | pathFromTo(vertexSource, vertexDestination) {
92 | if(!~this.vertices.indexOf(vertexSource) || this.vertices.indexOf(vertexDestination) === -1) {
93 | return console.log('Vertex not found');
94 | }
95 | const queue = [vertexSource];
96 | const visited = {[vertexSource]: true };
97 | const paths = {};
98 |
99 | while(queue.length) {
100 | const vertex = queue.shift();
101 | this.edges[vertex].forEach(vEdge => {
102 | if(!visited[vEdge]) {
103 | visited[vEdge] = true;
104 | queue.push(vEdge);
105 | // save paths between vertices
106 | paths[vEdge] = vertex;
107 | }
108 | });
109 | }
110 |
111 | let current = vertexDestination;
112 | const path = [];
113 | while (current) {
114 | path.push(current);
115 | current = paths[current];
116 | }
117 | return path.join('-');
118 | }
119 |
120 | print() {
121 | console.log(this.vertices.map(function(vertex) {
122 | return (`${vertex} -> ${this.edges[vertex].join(', ')}`).trim();
123 | }, this).join(' | '));
124 | }
125 | }
126 |
127 | const graph = new Graph();
128 | graph.addVertex(1);
129 | graph.addVertex(2);
130 | graph.addVertex(3);
131 | graph.addVertex(4);
132 | graph.addVertex(5);
133 | graph.addVertex(6);
134 | graph.print(); // 1 -> | 2 -> | 3 -> | 4 -> | 5 -> | 6 ->
135 | graph.addEdge(1, 2);
136 | graph.addEdge(1, 5);
137 | graph.addEdge(2, 3);
138 | graph.addEdge(2, 5);
139 | graph.addEdge(3, 4);
140 | graph.addEdge(4, 5);
141 | graph.addEdge(4, 6);
142 | graph.print(); // 1 -> 2, 5 | 2 -> 1, 3, 5 | 3 -> 2, 4 | 4 -> 3, 5, 6 | 5 -> 1, 2, 4 | 6 -> 4
143 | console.log('graph size (number of vertices):', graph.size()); // => 6
144 | console.log('graph relations (number of edges):', graph.relations()); // => 7
145 | graph.traverseDFS(1, vertex => { console.log(vertex); }); // => 1 2 3 4 5 6
146 | console.log('---');
147 | graph.traverseBFS(1, vertex => { console.log(vertex); }); // => 1 2 5 3 4 6
148 | graph.traverseDFS(0, vertex => { console.log(vertex); }); // => 'Vertex not found'
149 | graph.traverseBFS(0, vertex => { console.log(vertex); }); // => 'Vertex not found'
150 | console.log('path from 6 to 1:', graph.pathFromTo(6, 1)); // => 6-4-5-1
151 | console.log('path from 3 to 5:', graph.pathFromTo(3, 5)); // => 3-2-5
152 | graph.removeEdge(1, 2);
153 | graph.removeEdge(4, 5);
154 | graph.removeEdge(10, 11);
155 | console.log('graph relations (number of edges):', graph.relations()); // => 5
156 | console.log('path from 6 to 1:', graph.pathFromTo(6, 1)); // => 6-4-3-2-5-1
157 | graph.addEdge(1, 2);
158 | graph.addEdge(4, 5);
159 | console.log('graph relations (number of edges):', graph.relations()); // => 7
160 | console.log('path from 6 to 1:', graph.pathFromTo(6, 1)); // => 6-4-5-1
161 | graph.removeVertex(5);
162 | console.log('graph size (number of vertices):', graph.size()); // => 5
163 | console.log('graph relations (number of edges):', graph.relations()); // => 4
164 | console.log('path from 6 to 1:', graph.pathFromTo(6, 1)); // => 6-4-3-2-1
165 | graph.traverseDFS(1, (v) => console.log(`traverse DFS ${v}`) );
166 | graph.traverseBFS(1, (v) => console.log(`traverse BFS ${v}`) );
167 |
--------------------------------------------------------------------------------
/program-writing.md:
--------------------------------------------------------------------------------
1 | # JavaScript Program Writing
2 |
3 |
4 |
5 | ## Q. Write a program to swap two string variables without using temp variable?
6 |
7 | ```js
8 | Input: a = 'Hello', b = 'World'
9 | Output: a = 'World', b = 'Hello'
10 | ```
11 |
12 |
Answer
13 |
14 | **Solution 01:** ES6 only
15 |
16 | ```js
17 | let [a, b] = ["Hello", "World"];
18 |
19 | [b, a] = [a, b]; // Swap variables
20 |
21 | console.log(a, b); // World Hello
22 | ```
23 |
24 | **Solution 02:** ES5 compatible
25 |
26 | ```js
27 | /**
28 | * 1. a = b assigns the old value of b to a and yelds it, therefore [a, a=b] will be [a, b]
29 | * 2. the [0] operator yelds the first element of the array, which is a, so now b = [a,b][0] turns * into b = a
30 | */
31 | var a = "World";
32 | var b = "Hello";
33 |
34 | b = [a, (a = b)][0];
35 |
36 | console.log(a, b); // Hello World
37 | ```
38 |
39 |
40 |
41 |
44 |
45 | ## Q. Find the missing number in an array?
46 |
47 | ```js
48 | Input: [1, 6]
49 | Output: 2, 3, 4, 5
50 |
51 | Input: [1, 2, 10]
52 | Output: 3, 4, 5, 6, 7, 8, 9
53 |
54 | Input: [-1, -2, 3]
55 | Output: 2, 3, 4, 5
56 | ```
57 |
58 |
Answer
59 |
60 | ```js
61 | const findMissing = (arr) => {
62 | const missing = [];
63 | const max = Math.max(...arr); // highest number
64 | const min = Math.min(...arr); // lowest number
65 |
66 | for (let i = min; i <= max; i++) {
67 | if (!arr.includes(i)) {
68 | missing.push(i); // Adding numbers which are not in array
69 | }
70 | }
71 | return missing;
72 | };
73 |
74 | console.log(findMissing([1, 6]));
75 | ```
76 |
77 |
78 |
79 |
82 |
83 | ## Q. Write a function to count number of elements in nested array?
84 |
85 | ```js
86 | Input: [1, [2, [3, [4, [5, 6]]]]]
87 | Output: 6
88 | ```
89 |
90 |
Answer
91 |
92 | ```js
93 | let count = 0;
94 |
95 | function nestedCount(arr) {
96 | arr.forEach((val) => {
97 | if (Array.isArray(val)) {
98 | nestedCount(val);
99 | } else {
100 | count++;
101 | }
102 | });
103 | return count;
104 | }
105 |
106 | let input = [1, [2, [3, [4, [5, 6]]]]];
107 |
108 | console.log(nestedCount(input)); // 6
109 | ```
110 |
111 |
112 |
113 |
116 |
117 | ## Q. Write a function to return below details?
118 |
119 | ```js
120 | const characters = [
121 | {
122 | name: "Luke Skywalker",
123 | height: "172",
124 | mass: "77",
125 | eye_color: "blue",
126 | gender: "male",
127 | },
128 | {
129 | name: "Darth Vader",
130 | height: "202",
131 | mass: "136",
132 | eye_color: "yellow",
133 | gender: "male",
134 | },
135 | {
136 | name: "Leia Organa",
137 | height: "150",
138 | mass: "49",
139 | eye_color: "brown",
140 | gender: "female",
141 | },
142 | {
143 | name: "Anakin Skywalker",
144 | height: "188",
145 | mass: "84",
146 | eye_color: "blue",
147 | gender: "male",
148 | },
149 | ];
150 | ```
151 |
152 | **1. MAP:**
153 |
154 | * Get an array of all names
155 | * Get an array of all heights
156 | * Get an array of objects with just name and height properties
157 | * Get an array of all first names
158 |
159 |
Answer
160 |
161 | ```js
162 | // Get an array of all names
163 | const names = characters.map((character) => {
164 | return character.name;
165 | });
166 | console.log(names);
167 | ```
168 |
169 | ```js
170 | // Get an array of all heights
171 | const heights = characters.map((character) => {
172 | return character.height;
173 | });
174 | console.log(heights);
175 | ```
176 |
177 | ```js
178 | // Get an array of objects with just name and height properties
179 | const objects = characters.map((character) => {
180 | return { name: character.name, height: character.height };
181 | });
182 | console.log(objects);
183 | ```
184 |
185 | ```js
186 | // Get an array of all first names
187 | const firstNames = characters.map((character) => {
188 | return character.name.split(" ")[0];
189 | });
190 | console.log(firstNames);
191 | ```
192 |
193 |
194 |
195 |
198 |
199 | **2. REDUCE:**
200 |
201 | * Get the total mass of all characters
202 | * Get the total height of all characters
203 | * Get the total number of characters in all the character names
204 | * Get the total number of characters by eye color (hint. a map of eye color to count)
205 |
206 |
Answer
207 |
208 | ```js
209 | // Get the total mass of all characters
210 | const totalMass = characters.reduce((sum, character) => {
211 | return sum + parseInt(character.mass);
212 | }, 0);
213 | console.log(totalMass);
214 | ```
215 |
216 | ```js
217 | // Get the total height of all characters
218 | const totalHeight = characters.reduce((sum, character) => {
219 | return sum + parseInt(character.height);
220 | }, 0);
221 | console.log(totalHeight);
222 | ```
223 |
224 | ```js
225 | // Get the total number of characters in all the character names
226 | const characterCountByName = characters.reduce((result, character) => {
227 | if (typeof result[character.name] === "undefined") {
228 | result[character.name] = 1;
229 | } else {
230 | result[character.name] += 1;
231 | }
232 |
233 | return result;
234 | }, {});
235 | console.log(characterCountByName);
236 | ```
237 |
238 | ```js
239 | // Get the total number of characters by eye color
240 | const characterCountByEyeColor = characters.reduce((result, character) => {
241 | if (typeof result[character.eye_color] === "undefined") {
242 | result[character.eye_color] = 1;
243 | } else {
244 | result[character.eye_color] += 1;
245 | }
246 |
247 | return result;
248 | }, {});
249 | console.log(characterCountByEyeColor);
250 | ```
251 |
252 |
253 |
254 |
257 |
258 | **3. FILTER:**
259 |
260 | * Get characters with mass greater than 100
261 | * Get characters with height less than 200
262 | * Get all male characters
263 | * Get all female characters
264 |
265 |
Answer
266 |
267 | ```js
268 | // Get characters with mass greater than 100
269 | const characterMass = characters.filter((character) => {
270 | return character.mass > 100;
271 | }, {});
272 | console.log(characterMass);
273 | ```
274 |
275 | ```js
276 | // Get characters with height less than 200
277 | const characterHeight = characters.filter((character) => {
278 | return character.height < 200;
279 | }, {});
280 | console.log(characterHeight);
281 | ```
282 |
283 | ```js
284 | // Get all male characters
285 | const characterMale = characters.filter((character) => {
286 | return character.gender === 'male';
287 | }, {});
288 | console.log(characterMale);
289 | ```
290 |
291 | ```js
292 | // Get all female characters
293 | const characterFemale = characters.filter((character) => {
294 | return character.gender === 'female';
295 | }, {});
296 | console.log(characterFemale);
297 | ```
298 |
299 |
300 |
301 |
304 |
305 | **4. SORT:**
306 |
307 | * Sort by name
308 | * Sort by mass
309 | * Sort by height
310 | * Sort by gender
311 |
312 |
Answer
313 |
314 | ```js
315 | // Sort by Name
316 | const sortByName = characters.sort((a, b) => {
317 | if (a.name < b.name) {
318 | return -1;
319 | }
320 | });
321 | console.log(sortByName);
322 | ```
323 |
324 | ```js
325 | // Sort by Mass
326 | const sortByMass = characters.sort((a, b) => {
327 | if (parseInt(a.mass) < parseInt(b.mass)) {
328 | return -1;
329 | }
330 | });
331 | console.log(sortByMass);
332 | ```
333 |
334 | ```js
335 | // Sort by Height
336 | const sortByHeight = characters.sort((a, b) => {
337 | if (parseInt(a.height) < parseInt(b.height)) {
338 | return -1;
339 | }
340 | });
341 | console.log(sortByHeight);
342 | ```
343 |
344 | ```js
345 | // Sort by Gender
346 | const sortByGender = characters.sort((a, b) => {
347 | if (a.gender < b.gender) {
348 | return -1;
349 | }
350 | });
351 | console.log(sortByGender);
352 | ```
353 |
354 |
355 |
356 |
359 |
360 | **5. EVERY:**
361 |
362 | * Does every character have blue eyes?
363 | * Does every character have mass more than 40?
364 | * Is every character shorter than 200?
365 | * Is every character male?
366 |
367 |
Answer
368 |
369 | ```js
370 | // Does every character have blue eyes
371 | const checkBlueEye = characters.every(
372 | (character) => character.eye_color === "blue"
373 | );
374 | console.log(checkBlueEye);
375 | ```
376 |
377 | ```js
378 | // Does every character have mass more than 40
379 | const checkMass = characters.every((character) => character.mass > 40);
380 | console.log(checkMass);
381 | ```
382 |
383 | ```js
384 | // Is every character shorter than 200
385 | const checkHeight = characters.every((character) => character.height < 200);
386 | console.log(checkHeight);
387 | ```
388 |
389 | ```js
390 | // Is every character Male
391 | const checkGender = characters.every(
392 | (character) => character.gender === "male"
393 | );
394 | console.log(checkGender);
395 | ```
396 |
397 |
398 |
399 |
402 |
403 | **6. SOME:**
404 |
405 | * Is there at least one male character?
406 | * Is there at least one character with blue eyes?
407 | * Is there at least one character taller than 200?
408 | * Is there at least one character that has mass less than 50?
409 |
410 |
Answer
411 |
412 | ```js
413 | // Is there at least one male character
414 | const checkGender = characters.some(
415 | (character) => character.gender === "male"
416 | );
417 | console.log(checkGender);
418 | ```
419 |
420 | ```js
421 | // Is there at least one character with blue eyes
422 | const checkEye = characters.some(
423 | (character) => character.eye_color === "blue"
424 | );
425 | console.log(checkEye);
426 | ```
427 |
428 | ```js
429 | // Is there at least one character taller than 200
430 | const checkHeight = characters.some(
431 | (character) => character.height > 200
432 | );
433 | console.log(checkHeight);
434 | ```
435 |
436 | ```js
437 | // Is there at least one character that has mass less than 50
438 | const checkMass = characters.some(
439 | (character) => character.mass < 50
440 | );
441 | console.log(checkMass);
442 | ```
443 |
444 |
445 |
446 |
449 |
450 | ## Q. Replace first two elements in array using splice()?
451 |
452 | **Examples:**
453 |
454 | ```js
455 | Input: ["Angular", "JavaScript", "NodeJS", "MongoDB"];
456 | Output: ["React", "Redux", "NodeJS", "MongoDB"];
457 | ```
458 |
459 |
Answer
460 |
461 | ```js
462 | let arr = ["Angular", "JavaScript", "NodeJS", "MongoDB"];
463 |
464 | arr.splice(0, 2, "React", "Redux");
465 | console.log(arr);
466 | ```
467 |
468 |
469 |
470 |
473 |
474 | ## Q. Write a function to check whether given string is a Palindrome or not?
475 |
476 | **Examples:**
477 |
478 | ```js
479 | Input: "aba"
480 | Output: "Palindrome"
481 |
482 | Input: "ABCDCBA"
483 | Output: "Palindrome"
484 |
485 | Input: "Hello"
486 | Output: "Not a Palindrome"
487 | ```
488 |
489 |
Answer
490 |
491 | ```js
492 | function checkPalindrome(str) {
493 | for (let i = 0; i < str.length / 2; i++) {
494 | // check if first and last character are same
495 | if (str[i] !== str[str.length - 1 - i]) {
496 | return "Not a palindrome";
497 | }
498 | }
499 | return "Palindrome";
500 | }
501 |
502 | console.log(checkPalindrome("aba"));
503 | console.log(checkPalindrome("ABCDCBA"));
504 | console.log(checkPalindrome("Hello"));
505 | ```
506 |
507 |
508 |
509 |
512 |
513 | ## Q. Write a function to find out number of occurrences of a character in a given string?
514 |
515 | **Examples:**
516 |
517 | ```js
518 | Input: 'm', 'how many times does the character occur in this sentence?'
519 | Output: 2
520 |
521 | Input: 'h', 'how many times does the character occur in this sentence?'
522 | Output: 4
523 |
524 | Input: '?', 'how many times does the character occur in this sentence?'
525 | Output: 1
526 | ```
527 |
528 |
Answer
529 |
530 | **Solution 01:** Using for Loop
531 |
532 | ```js
533 | function countCharacter(str, ch) {
534 | let count = 0;
535 | for (let i = 0; i < str.length; i++) {
536 | // check if the character is at that position
537 | if (str.charAt(i) === ch) {
538 | count += 1;
539 | }
540 | }
541 | return count;
542 | }
543 |
544 | console.log(countCharacter(str, ch));
545 | ```
546 |
547 | **Solution 02:** Using Regex
548 |
549 | ```js
550 | function countCharacter(str, ch) {
551 | // creating a pattern
552 | const re = new RegExp(ch, "g");
553 | return str.match(re).length;
554 | }
555 |
556 | console.log(countCharacter(str, ch));
557 | ```
558 |
559 | **Solution 03:** Using split() function
560 |
561 | ```js
562 | function countCharacter(str, ch) {
563 | return str.split(ch).length - 1;
564 | }
565 |
566 | console.log(countCharacter(str, ch));
567 | ```
568 |
569 | **Solution 04:** Using filter() function
570 |
571 | ```js
572 | function countCharacter(str, ch) {
573 | return [...str].filter((x) => x === ch).length;
574 | }
575 |
576 | console.log(countCharacter(str, ch));
577 | ```
578 |
579 |
580 |
581 |
584 |
585 | ## Q. Write a function that takes a string as argument and increment each letter to the next letter in the alphabet?
586 |
587 | **Examples:**
588 |
589 | ```js
590 | Input: 'aaa'
591 | Output: 'bbb'
592 |
593 | Input: 'abcde'
594 | Output: 'bcdef'
595 |
596 | Input: 'hello'
597 | Output: 'ifmmp'
598 | ```
599 |
600 |
Answer
601 |
602 | ```js
603 | function nextChar(c) {
604 | return String.fromCharCode(c.charCodeAt(0) + 1);
605 | }
606 |
607 | const transform = (str) => {
608 | let word = "";
609 | for (let i = 0; i < str.length; i++) {
610 | word += nextChar(str[i]);
611 | }
612 | return word;
613 | };
614 |
615 | const input = "aaa";
616 | console.log(transform(input)); // bbb
617 | ```
618 |
619 |
620 |
621 |
624 |
625 | ## Q. Write a function that takes a string as argument and remove the first 'n' characters from it?
626 |
627 | **Examples:**
628 |
629 | ```js
630 | Input: 'Hello World', 6
631 | Output: 'World'
632 |
633 | Input: '12345', 2
634 | Output: '345'
635 |
636 | Input: 'JavaScript', 4
637 | Output: 'Script'
638 | ```
639 |
640 |
Answer
641 |
642 | **Solution 01:** Using substring() method
643 |
644 | ```js
645 | function transform(str, n) {
646 | return str.substring(n);
647 | }
648 |
649 | console.log(transform("Hello World", 6));
650 | ```
651 |
652 | **Solution 02:** Using slice() method
653 |
654 | ```js
655 | function transform(str, n) {
656 | return str.slice(n);
657 | }
658 |
659 | console.log(transform("Hello World", 6));
660 | ```
661 |
662 | **Solution 03:** Using substr() method
663 |
664 | ```js
665 | function transform(str, n) {
666 | return str.substr(n);
667 | }
668 |
669 | console.log(transform("Hello World", 6));
670 | ```
671 |
672 |
673 |
674 |
677 |
678 | ## Q. Write a function to transform string array into group by its length?
679 |
680 | **Examples:**
681 |
682 | ```js
683 | Input: ['one', 'two', 'three']
684 | Output: {3: ["one", "two"], 5: ["three"]}
685 | ```
686 |
687 |
Answer
688 |
689 | ```js
690 | const result = {};
691 |
692 | for (let elemement of arr) {
693 | if (!(elemement.length in result)) {
694 | result[elemement.length] = [];
695 | }
696 | result[elemement.length].push(elemement);
697 | }
698 |
699 | console.log(result);
700 | ```
701 |
702 |
703 |
704 |
707 |
708 | ## Q. Write a function to transform json in group by parameter?
709 |
710 | **Examples:**
711 |
712 | ```js
713 | [
714 | { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5"},
715 | { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10"},
716 | { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15"},
717 | { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20"},
718 | { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25"},
719 | { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30"}
720 | ];
721 |
722 | // Output: Group By 'Phase'
723 | {
724 | 'Phase 1': [
725 | { Phase: 'Phase 1', Step: 'Step 1', Task: 'Task 1', Value: '5' },
726 | { Phase: 'Phase 1', Step: 'Step 1', Task: 'Task 2', Value: '10' },
727 | { Phase: 'Phase 1', Step: 'Step 2', Task: 'Task 1', Value: '15' },
728 | { Phase: 'Phase 1', Step: 'Step 2', Task: 'Task 2', Value: '20' }
729 | ],
730 | 'Phase 2': [
731 | { Phase: 'Phase 2', Step: 'Step 1', Task: 'Task 1', Value: '25' },
732 | { Phase: 'Phase 2', Step: 'Step 1', Task: 'Task 2', Value: '30' }
733 | ]
734 | }
735 | ```
736 |
737 |
Answer
738 |
739 | ```js
740 | const groupBy = function (items, key) {
741 | return items.reduce(function (result, item) {
742 | (result[item[key]] = result[item[key]] || []).push(item);
743 | return result;
744 | }, {});
745 | };
746 |
747 | console.log(groupBy(arry, "Phase"));
748 | ```
749 |
750 |
751 |
752 |
755 |
756 | ## Q. Write a function to transform json in group by id?
757 |
758 | **Examples:**
759 |
760 | ```js
761 | Input:
762 |
763 | [
764 | { id: 1, type: "ADD" },
765 | { id: 1, type: "CHANGE" },
766 | { id: 2, type: "ADD" },
767 | { id: 3, type: "ADD" },
768 | { id: 3, type: "CHANGE" },
769 | { id: 2, type: "REMOVE" },
770 | { id: 3, type: "CHANGE" },
771 | { id: 1, type: "REMOVE" },
772 | ];
773 |
774 | Output:
775 |
776 | [
777 | { id: 1, type: ["ADD", "CHANGE", "REMOVE"] },
778 | { id: 2, type: ["ADD", "REMOVE"] },
779 | { id: 3, type: ["ADD", "CHANGE", "CHANGE"] },
780 | ];
781 | ```
782 |
783 |
Answer
784 |
785 | ```js
786 | const groupBy = (arr = []) => {
787 | const result = [];
788 | const map = {};
789 | for (let i = 0, j = arr.length; i < j; i++) {
790 | let element = arr[i];
791 | if (!(element.id in map)) {
792 | map[element.id] = {id: element.id, type: []};
793 | result.push(map[element.id]);
794 | };
795 | map[element.id].type.push(element.type);
796 | };
797 | return result;
798 | };
799 |
800 | console.log(groupBy(arr));
801 | ```
802 |
803 |
804 |
805 |
808 |
809 | ## Q. Write a function to implement Math.pow() function?
810 |
811 | **Input: (2)
3 **
812 | **Output: 8**
813 |
814 |
Answer
815 |
816 | ```js
817 | function powerOf(base, exponent) {
818 | let result = 1;
819 | for (let i = 1; i <= exponent; i++) {
820 | result = result * base;
821 | }
822 | return result;
823 | }
824 |
825 | console.log(powerOf(2, 3));
826 | ```
827 |
828 |
829 |
830 |
833 |
834 | ## Q. Write a function to remove duplicates from an integer array in JavaScript?
835 |
836 | ```js
837 | Input: [3, 2, 4, 5, 8, 9, 3, 8, 1, 7, 8, 4, 3, 2]
838 | Output: [1, 2, 3, 4, 5, 7, 8, 9]
839 | ```
840 |
841 |
Answer
842 |
843 | ```js
844 | function removeDuplicates(arr) {
845 | let result = [];
846 | arr.forEach((element) => {
847 | if (!result.includes(element)) {
848 | result.push(element);
849 | }
850 | });
851 | return result;
852 | }
853 |
854 | console.log(removeDuplicates(arr));
855 | ```
856 |
857 |
858 |
859 |
862 |
863 | ## Q. Write a function to find non-repetitive numbers in a given array?
864 |
865 | **Examples:**
866 |
867 | ```js
868 | Input:
869 | [2, 3, 4, 3, 3, 2, 4, 9, 1, 2, 5, 5]
870 |
871 | Output:
872 | [9, 1]
873 | ```
874 |
875 |
Answer
876 |
877 | ```js
878 | // Creating Object with number of occurance of each elements
879 | const count = {};
880 | for(let element of arr) {
881 | if(count[element]) {
882 | count[element] += 1;
883 | } else {
884 | count[element] = 1;
885 | }
886 | }
887 |
888 | // Iterate Unique elements
889 | for(let key in count) {
890 | if(count[key] === 1) {
891 | console.log(key + '->' + count[key]);
892 | }
893 | }
894 | ```
895 |
896 |
897 |
898 |
901 |
902 | ## Q. Write a function to accept string and find first non-repeated character?
903 |
904 | **Examples:**
905 |
906 | ```js
907 | Input: 'aabcbd'
908 | Output: 'c'
909 |
910 | Input: 'teeter'
911 | Output: 'r'
912 |
913 | Input: 'abacddbec'
914 | Output: 'e'
915 | ```
916 |
917 |
Answer
918 |
919 | ```js
920 | function firstNonRepeatingCharacter(str) {
921 | for (let i = 0; i < str.length; i++) {
922 | let char = str[i];
923 | if (str.indexOf(char) === str.lastIndexOf(char)) {
924 | return char;
925 | }
926 | }
927 | return "_";
928 | }
929 |
930 | console.log(firstNonRepeatingCharacter("aabcbd")); // c
931 |
932 | console.log(firstNonRepeatingCharacter("teeter")); // r
933 |
934 | console.log(firstNonRepeatingCharacter("abacddbec")); // e
935 |
936 | ```
937 |
938 |
939 |
940 |
943 |
944 | ## Q. Write a function to sort an integer array?
945 |
946 | **Examples:**
947 |
948 | ```js
949 | Input: [ 53, 11, 34, 12, 18 ]
950 | Output: [ 11, 12, 18, 34, 53 ];
951 | ```
952 |
953 |
Answer
954 |
955 | **Solution 1:**
956 |
957 | ```js
958 | /**
959 | * Sort elements using compare method
960 | */
961 | let arr = [53, 11, 34, 12, 18];
962 |
963 | arr.sort((a, b) => {
964 | return a - b;
965 | });
966 |
967 | console.log(arr);
968 | ```
969 |
970 | **Solution 2:**
971 |
972 | ```js
973 | /**
974 | * Optimized implementation of bubble sort Algorithm
975 | */
976 | function bubbleSort(arr) {
977 | let isSwapped = false;
978 |
979 | for (let i = 0; i < arr.length; i++) {
980 | isSwapped = false;
981 |
982 | for (let j = 0; j < arr.length; j++) {
983 | if (arr[j] > arr[j + 1]) {
984 | let temp = arr[j];
985 | arr[j] = arr[j + 1];
986 | arr[j + 1] = temp;
987 | isSwapped = true;
988 | }
989 | }
990 |
991 | // If no two elements were swapped by inner loop, then break
992 | if (!isSwapped) {
993 | break;
994 | }
995 | }
996 | return arr;
997 | }
998 |
999 | console.log(bubbleSort([53, 11, 34, 12, 18]));
1000 | ```
1001 |
1002 |
1003 |
1004 |
1007 |
1008 | ## Q. Write a program to read file and count word, unique word and search string?
1009 |
1010 | **Examples:**
1011 |
1012 | ```js
1013 | Input: file.txt
1014 | Search String: 'Lipsum'
1015 | Output:
1016 | ┌──────────────┬────────┐
1017 | │ (index) │ Values │
1018 | ├──────────────┼────────┤
1019 | │ Word Count │ 22 │
1020 | │ Unique Words │ 17 │
1021 | │ searchString │ 18 │
1022 | └──────────────┴────────┘
1023 | ```
1024 |
1025 |
Answer
1026 |
1027 | ```js
1028 | const fs = require("fs");
1029 |
1030 | // #1 count the number of words
1031 | const wordCount = (string) => string.split(" ").length;
1032 |
1033 | // #2 count the number of unique words
1034 | const uniqueWords = (txt) => new Set(txt.toLowerCase().match(/\w+/g)).size;
1035 |
1036 | // #3 count the search string
1037 | const searchString = (string) => {
1038 | let count = 0;
1039 | let words = string.split(" ");
1040 |
1041 | for (let i = 0; i < words.length; i++) {
1042 | if (words[i].indexOf("ispsum")) {
1043 | count++;
1044 | }
1045 | }
1046 | return count;
1047 | };
1048 |
1049 | fs.readFile("file.txt", "utf8", function (err, data) {
1050 | if (err) throw err;
1051 | console.log("The text in the file:\n\n", data, "\n");
1052 | // store results in an object to present the log better
1053 | let result = {
1054 | "Word Count": wordCount(data),
1055 | "Unique Words": uniqueWords(data),
1056 | searchString: searchString(data),
1057 | };
1058 | console.table(result);
1059 | });
1060 | ```
1061 |
1062 |
1063 |
1064 |
1067 |
1068 | ## Q. Find the most repeated elements in given array?
1069 |
1070 | **Examples:**
1071 |
1072 | ```js
1073 | Input: [1, 2, 3, 4, 5, 1]
1074 | Output: [1, 2]
1075 |
1076 | Input: [12, 5, 6, 76, 23, 12, 34, 5, 23, 34, 65, 34, 22, 67, 34]
1077 | Output: [34, 4]
1078 |
1079 | Input: [2, 1, 10, 7, 10, 3, 10, 8, 7, 3, 10, 5, 4, 6, 7, 9, 9, 9, 9, 6, 3, 7, 6, 9, 8, 9, 10]
1080 | Output: [9, 6]
1081 | ```
1082 |
1083 |
Answer
1084 |
1085 | ```js
1086 | function mostFrequentElement(array) {
1087 | let count = {};
1088 | let maxElement = array[0];
1089 | let maxCount = 1;
1090 |
1091 | for (let i = 0; i < array.length; i++) {
1092 | let element = array[i];
1093 | if (count[element]) {
1094 | count[element] += 1;
1095 | } else {
1096 | count[element] = 1;
1097 | }
1098 | if (count[element] > maxCount) {
1099 | maxElement = element;
1100 | maxCount = count[element];
1101 | }
1102 | }
1103 | return [maxElement, maxCount];
1104 | }
1105 |
1106 | console.log(mostFrequentElement([12, 5, 6, 76, 23, 12, 34, 5, 23, 34, 65, 34, 22, 67, 34])); // [34, 4]
1107 | ```
1108 |
1109 |
1110 |
1111 |
1114 |
1115 | ## Q. Filter users with age between 15 and 30 from the given json array?
1116 |
1117 | **Examples:**
1118 |
1119 | ```js
1120 | Input:
1121 | [
1122 | {
1123 | a: { name: "John", age: 25 },
1124 | b: { name: "Peter", age: 45 },
1125 | c: { name: "Bob", age: 20 },
1126 | },
1127 | {
1128 | a: { name: "Ram", age: 25 },
1129 | b: { name: "Krish", age: 45 },
1130 | c: { name: "Roshan", age: 20 },
1131 | },
1132 | ];
1133 |
1134 | Output:
1135 | [
1136 | [ { name: 'John', age: 25 }, { name: 'Bob', age: 20 } ],
1137 | [ { name: 'Ram', age: 25 }, { name: 'Roshan', age: 20 } ]
1138 | ]
1139 | ```
1140 |
1141 |
Answer
1142 |
1143 | ```js
1144 | function filterUser(arr) {
1145 | const users = [];
1146 |
1147 | for (let i = 0; i < arr.length; i++) {
1148 | let element = arr[i];
1149 | let user = Object.values(element).filter((key) => {
1150 | return key.age > 15 && key.age < 30;
1151 | });
1152 | users.push(user);
1153 | }
1154 | return users;
1155 | }
1156 | ```
1157 |
1158 |
1159 |
1160 |
1163 |
1164 | ## Q. Write a function to accept argument like `sum(num1)(num2);` or `sum(num1,num2);`
1165 |
1166 | **Examples:**
1167 |
1168 | ```js
1169 | Input: sum(10)(20);
1170 | Output: 30
1171 | Explanation: 10 + 20 = 30
1172 |
1173 | Input: sum(10, 20);
1174 | Output: 30
1175 | Explanation: 10 + 20 = 30
1176 | ```
1177 |
1178 |
Answer
1179 |
1180 | ```js
1181 | function sum(x, y) {
1182 | if (y !== undefined) {
1183 | return x + y;
1184 | } else {
1185 | return function (y) {
1186 | return x + y;
1187 | };
1188 | }
1189 | }
1190 |
1191 | console.log(sum(10, 20));
1192 | console.log(sum(10)(20));
1193 | ```
1194 |
1195 | **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-1-ypmjhl?file=/src/index.js)**
1196 |
1197 |
1198 |
1199 |
1202 |
1203 | ## Q. Write a function to get the difference between two arrays?
1204 |
1205 | **Example:**
1206 |
1207 | ```js
1208 | Input:
1209 | ['a', 'b'];
1210 | ['a', 'b', 'c', 'd'];
1211 |
1212 | Output:
1213 | ["c", "d"]
1214 | ```
1215 |
1216 |
Answer
1217 |
1218 | ```js
1219 | let arr1 = ['a', 'b'];
1220 | let arr2 = ['a', 'b', 'c', 'd'];
1221 |
1222 | let difference = arr2.filter(x => !arr1.includes(x));
1223 | ```
1224 |
1225 |
1226 |
1227 |
1230 |
1231 | ## Q. Write a function to accept argument like `[array1].diff([array2]);`
1232 |
1233 | **Example:**
1234 |
1235 | ```js
1236 | Input: [1, 2, 3, 4, 5, 6].diff([3, 4, 5]);
1237 | Output: [1, 2, 6];
1238 | ```
1239 |
1240 |
Answer
1241 |
1242 | ```js
1243 | Array.prototype.diff = function (a) {
1244 | return this.filter(function (i) {
1245 | return a.indexOf(i) < 0;
1246 | });
1247 | };
1248 |
1249 | const dif1 = [1, 2, 3, 4, 5, 6].diff([3, 4, 5]);
1250 | console.log(dif1); // => [1, 2, 6]
1251 | ```
1252 |
1253 |
1254 |
1255 |
1258 |
1259 | ## Q. Validate file size and extension before file upload in JavaScript?
1260 |
1261 | ```js
1262 | Output:
1263 |
1264 | File Name: pic.jpg
1265 | File Size: 1159168 bytes
1266 | File Extension: jpg
1267 | ```
1268 |
1269 |
Answer
1270 |
1271 | ```html
1272 |
1273 |
1274 |
1275 |
1289 |
1290 |
1291 |
1292 |
1302 |
1303 |
1304 |
1305 | ```
1306 |
1307 | **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-file-upload-fj17kh?file=/index.html)**
1308 |
1309 |
1310 |
1311 |
1314 |
1315 | ## Q. Create a captcha using javascript?
1316 |
1317 |
1318 |
1319 |
1320 |
1321 |
Answer
1322 |
1323 | ```html
1324 |
1325 |
1326 |
1327 | JavaScript Captcha Generator
1328 |
1329 |
1342 |
1343 |
1344 |
1345 | Refresh
1346 |
1347 |
1348 | ```
1349 |
1350 | **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-captcha-mzyi2n?file=/index.html)**
1351 |
1352 |
1353 |
1354 |
1357 |
1358 | ## Q. Create a stopwatch in javascript?
1359 |
1360 |
1361 |
1362 |
1363 |
1364 |
Answer
1365 |
1366 | ```html
1367 |
1368 |
1369 |
1370 | Stopwatch Example
1371 |
1372 |
1373 |
1374 | Time: 00:00:00
1375 | Start
1376 | Stop
1377 | Reset
1378 |
1379 |
1434 |
1435 |
1436 | ```
1437 |
1438 | **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-stopwatch-j6in1i?file=/index.html)**
1439 |
1440 |
1441 |
1442 |
1445 |
1446 | ## Q. Write a program to reverse a string?
1447 |
1448 | ```js
1449 | Input: Hello
1450 | Output: olleH
1451 | ```
1452 |
1453 |
Answer
1454 |
1455 | ```js
1456 | function reverseString(str) {
1457 | let stringRev = "";
1458 | for (let i = str.length; i >= 0; i--) {
1459 | stringRev = stringRev + str.charAt(i);
1460 | }
1461 | return stringRev;
1462 | }
1463 | console.log(reverseString("Hello"));
1464 | ```
1465 |
1466 | **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-reversestring-sgm1ip?file=/src/index.js)**
1467 |
1468 |
1469 |
1470 |
1473 |
1474 | ## Q. Given a string, reverse each word in the sentence
1475 |
1476 | **Example:**
1477 |
1478 | ```js
1479 | Input: "Hello World";
1480 | Output: "olleH dlroW";
1481 | ```
1482 |
1483 |
Answer
1484 |
1485 | ```js
1486 | const str = "Hello World";
1487 |
1488 | let reverseEntireSentence = reverseBySeparator(str, "");
1489 |
1490 | console.log(reverseBySeparator(reverseEntireSentence, " "));
1491 |
1492 | function reverseBySeparator(string, separator) {
1493 | return string.split(separator).reverse().join(separator);
1494 | }
1495 | ```
1496 |
1497 |
1498 |
1499 |
1502 |
1503 | ## Q. Create a Promise to accept argument and make it resolve if the argument matches with predefined condition?
1504 |
1505 | ```js
1506 | Input: ['Maruti Suzuki', 'Hyundai', 'Tata Motors', 'Kia', 'Mahindra & Mahindra'];
1507 | Key: Maruti Suzuki
1508 | Output:
1509 | Maruti Suzuki
1510 | ```
1511 |
1512 |
Answer
1513 |
1514 | ```js
1515 | async function myCars(name) {
1516 | const promise = new Promise((resolve, reject) => {
1517 | name === "Maruti Suzuki" ? resolve(name) : reject(name);
1518 | });
1519 |
1520 | const result = await promise;
1521 | console.log(result); // "resolved!"
1522 | }
1523 |
1524 | myCars("Maruti Suzuki");
1525 | ```
1526 |
1527 | **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-promise-1tmrnp?file=/src/index.js)**
1528 |
1529 |
1530 |
1531 |
1534 |
1535 | ## Q. Write a function to merge two JavaScript Object dynamically?
1536 |
1537 | **Example:**
1538 |
1539 | ```js
1540 | Input:
1541 |
1542 | {
1543 | name: "Tanvi",
1544 | age: 28
1545 | };
1546 |
1547 | {
1548 | addressLine1: "Some Location x",
1549 | addressLine2: "Some Location y",
1550 | city: "Bangalore"
1551 | };
1552 |
1553 | Output:
1554 |
1555 | // Now person should have 5 properties
1556 | {
1557 | name: "Tanvi",
1558 | age: 28,
1559 | addressLine1: "Some Location x",
1560 | addressLine2: "Some Location y",
1561 | city: "Bangalore"
1562 | }
1563 | ```
1564 |
1565 |
Answer
1566 |
1567 | ```js
1568 | /**
1569 | * Using Spread Object
1570 | */
1571 |
1572 | const person = {
1573 | name: "Tanvi",
1574 | age: 28
1575 | };
1576 |
1577 | const address = {
1578 | addressLine1: "Some Location x",
1579 | addressLine2: "Some Location y",
1580 | city: "Bangalore"
1581 | };
1582 |
1583 |
1584 | const merged = {...person, ...address};
1585 |
1586 | console.log(merged);
1587 | // {name: "Tanvi", age: 28, addressLine1: "Some Location x", addressLine2: "Some Location y", city: "Bangalore"}
1588 | ```
1589 |
1590 | **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-shallow-vs-deep-copy-ik5b7h?file=/src/index.js)**
1591 |
1592 |
1593 |
1594 |
1597 |
1598 | ## Q. Being told that an unsorted array contains (n - 1) of n consecutive numbers (where the bounds are defined), find the missing number in O(n) time?
1599 |
1600 | **Example:**
1601 |
1602 | ```js
1603 | Input:
1604 | array = [2, 5, 1, 4, 9, 6, 3, 7];
1605 | upperBound = 9;
1606 | lowerBound = 1;
1607 |
1608 | Output:
1609 | 8
1610 | ```
1611 |
1612 |
Answer
1613 |
1614 | ```js
1615 | /**
1616 | * Find theoretical sum of the consecutive numbers using a variation of Gauss Sum.
1617 | * Formula: [(Max * (Max + 1)) / 2] - [(Min * (Min - 1)) / 2];
1618 | * Max is the upper bound and Min is the lower bound
1619 | */
1620 | function findMissingNumber(arrayOfIntegers, upperBound, lowerBound) {
1621 |
1622 | var sumOfIntegers = 0;
1623 | for (var i = 0; i < arrayOfIntegers.length; i++) {
1624 | sumOfIntegers += arrayOfIntegers[i];
1625 | }
1626 |
1627 | upperLimitSum = (upperBound * (upperBound + 1)) / 2;
1628 | lowerLimitSum = (lowerBound * (lowerBound - 1)) / 2;
1629 |
1630 | theoreticalSum = upperLimitSum - lowerLimitSum;
1631 |
1632 | return theoreticalSum - sumOfIntegers;
1633 | }
1634 | ```
1635 |
1636 |
1637 |
1638 |
1641 |
1642 | ## Q. Write a function to remove duplicates from an array in JavaScript?
1643 |
1644 | ```js
1645 | Input: ['John', 'Paul', 'George', 'Ringo', 'John']
1646 | Output: ['John', 'Paul', 'George', 'Ringo']
1647 | ```
1648 |
1649 |
Answer
1650 |
1651 | **1. Using set():**
1652 |
1653 | ```js
1654 | const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
1655 |
1656 | let unique = [...new Set(names)];
1657 | console.log(unique); // 'John', 'Paul', 'George', 'Ringo'
1658 | ```
1659 |
1660 | **2. Using filter():**
1661 |
1662 | ```js
1663 | const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
1664 |
1665 | let x = (names) => names.filter((v,i) => names.indexOf(v) === i)
1666 | x(names); // 'John', 'Paul', 'George', 'Ringo'
1667 | ```
1668 |
1669 | **3. Using forEach():**
1670 |
1671 | ```js
1672 | const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
1673 |
1674 | function removeDups(names) {
1675 | let unique = {};
1676 | names.forEach(function(i) {
1677 | if(!unique[i]) {
1678 | unique[i] = true;
1679 | }
1680 | });
1681 | return Object.keys(unique);
1682 | }
1683 |
1684 | removeDups(names); // 'John', 'Paul', 'George', 'Ringo'
1685 | ```
1686 |
1687 |
1688 |
1689 |
1692 |
1693 | ## Q. Use a closure to create a private counter?
1694 |
1695 | **Example:**
1696 |
1697 | You can create a function within an outer function (a closure) that allows you to update a private variable but the variable wouldn\'t be accessible from outside the function without the use of a helper function.
1698 |
1699 |
Answer
1700 |
1701 | ```js
1702 | function counter() {
1703 | var _counter = 0;
1704 | // return an object with several functions that allow you
1705 | // to modify the private _counter variable
1706 | return {
1707 | add: function (increment) {
1708 | _counter += increment;
1709 | },
1710 | retrieve: function () {
1711 | return "The counter is currently at: " + _counter;
1712 | },
1713 | };
1714 | }
1715 |
1716 | // error if we try to access the private variable like below
1717 | // _counter;
1718 |
1719 | // usage of our counter function
1720 | var c = counter();
1721 | c.add(5);
1722 | c.add(9);
1723 |
1724 | // now we can access the private variable in the following way
1725 | c.retrieve(); // => The counter is currently at: 14
1726 | ```
1727 |
1728 |
1729 |
1730 |
1733 |
1734 | ## Q. Write a function to divide an array into multiple equal parts?
1735 |
1736 | **Example:**
1737 |
1738 | ```js
1739 | Input: [10, 20, 30, 40, 50];
1740 | Length: 3
1741 | Output:
1742 | [10, 20, 30]
1743 | [40, 50]
1744 | ```
1745 |
1746 |
Answer
1747 |
1748 | ```js
1749 | const arr = [10, 20, 30, 40, 50];
1750 | let lenth = 3;
1751 |
1752 | function split(len) {
1753 | while (arr.length > 0) {
1754 | console.log(arr.splice(0, len));
1755 | }
1756 | }
1757 | split(lenth);
1758 | ```
1759 |
1760 | **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/split-array-5od3rz)**
1761 |
1762 |
1763 |
1764 |
1767 |
1768 | ## Q. Write a random integers function to print integers with in a range?
1769 |
1770 | **Example:**
1771 |
1772 | ```js
1773 | Input: 1, 100
1774 | Output: 63
1775 | ```
1776 |
1777 |
Answer
1778 |
1779 | ```js
1780 | /**
1781 | * function to return a random number
1782 | * between min and max range
1783 | */
1784 | function randomInteger(min, max) {
1785 | return Math.floor(Math.random() * (max - min + 1) ) + min;
1786 | }
1787 |
1788 | randomInteger(1, 100); // returns a random integer from 1 to 100
1789 | ```
1790 |
1791 | **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-random-integers-yd1cy8?file=/src/index.js)**
1792 |
1793 |
1794 |
1795 |
1798 |
1799 | ## Q. Write a function to convert decimal number to binary number?
1800 |
1801 | **Examples:**
1802 |
1803 | ```js
1804 | Input: 10
1805 | Output: 1010
1806 |
1807 | Input: 7
1808 | Output: 111
1809 | ```
1810 |
1811 |
Answer
1812 |
1813 | ```js
1814 | function DecimalToBinary(number) {
1815 | let bin = 0;
1816 | let rem,
1817 | i = 1;
1818 | while (number !== 0) {
1819 | rem = number % 2;
1820 | number = parseInt(number / 2);
1821 | bin = bin + rem * i;
1822 | i = i * 10;
1823 | }
1824 | console.log(`Binary: ${bin}`);
1825 | }
1826 |
1827 | DecimalToBinary(10);
1828 | ```
1829 |
1830 | **Example 02:** Convert Decimal to Binary Using `toString()`
1831 |
1832 | ```js
1833 | let val = 10;
1834 |
1835 | console.log(val.toString(2)); // 1010 ==> Binary Conversion
1836 | console.log(val.toString(8)); // 12 ==> Octal Conversion
1837 | console.log(val.toString(16)); // A ==> Hexadecimal Conversion
1838 | ```
1839 |
1840 | **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-decimal-to-binary-uhyi8t?file=/src/index.js)**
1841 |
1842 |
1843 |
1844 |
1847 |
1848 | ## Q. Write a function make first letter of the string in an uppercase?
1849 |
1850 | **Example:**
1851 |
1852 | ```js
1853 | Input: hello world
1854 | Output: Hello World
1855 | ```
1856 |
1857 |
Answer
1858 |
1859 | You can create a function which uses chain of string methods such as charAt, toUpperCase and slice methods to generate a string with first letter in uppercase.
1860 |
1861 | ```js
1862 | function capitalizeFirstLetter(string) {
1863 | let arr = string.split(" ");
1864 | for (let i = 0; i < arr.length; i++) {
1865 | arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
1866 | }
1867 | return arr.join(" ");
1868 | }
1869 |
1870 | console.log(capitalizeFirstLetter("hello world")); // Hello World
1871 | ```
1872 |
1873 | **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-capitalizefirstletter-dpjhky?file=/src/index.js)**
1874 |
1875 |
1876 |
1877 |
1880 |
1881 | ## Q. Write a function which will test string as a literal and as an object?
1882 |
1883 | **Examples:**
1884 |
1885 | ```js
1886 | Input: const ltrlStr = "Hi I am string literal";
1887 | Output: It is a string literal
1888 |
1889 | Input: const objStr = new String("Hi I am string object");
1890 | Output: It is an object of string
1891 | ```
1892 |
1893 |
Answer
1894 |
1895 | The `typeof` operator can be use to test string literal and `instanceof` operator to test String object.
1896 |
1897 | ```js
1898 | function check(str) {
1899 | if (str instanceof String) {
1900 | return "It is an object of string";
1901 | } else {
1902 | if (typeof str === "string") {
1903 | return "It is a string literal";
1904 | } else {
1905 | return "another type";
1906 | }
1907 | }
1908 | }
1909 |
1910 | const ltrlStr = "Hi I am string literal";
1911 | const objStr = new String("Hi I am string object");
1912 |
1913 | console.log(check(ltrlStr)); // It is a string literal
1914 | console.log(check(objStr)); // It is an object of string
1915 | ```
1916 |
1917 | **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-literal-vs-object-978dqw?file=/src/index.js)**
1918 |
1919 |
1920 |
1921 |
1924 |
1925 | ## Q. Write a program to reverse an array?
1926 |
1927 | ```js
1928 | Input: ["Apple", "Banana", "Mango", "Orange"];
1929 | Output: ["Orange", "Mango", "Banana", "Apple"];
1930 | ```
1931 |
1932 |
Answer
1933 |
1934 | You can use reverse() method is used reverse the elements in an array. This method is useful to sort an array in descending order.
1935 |
1936 | ```js
1937 | const fruits = ["Apple", "Banana", "Mango", "Orange"];
1938 |
1939 | const reversed = fruits.reverse();
1940 | console.log(reversed); // ["Orange", "Mango", "Banana", "Apple"]
1941 | ```
1942 |
1943 |
1944 |
1945 |
1948 |
1949 | ## Q. Write a program to find min and max value in an array?
1950 |
1951 | **Example:**
1952 |
1953 | ```js
1954 | Input: [50, 20, 70, 60, 45, 30];
1955 | Output:
1956 | Min: 20
1957 | Max: 70
1958 | ```
1959 |
1960 |
Answer
1961 |
1962 | You can use `Math.min` and `Math.max` methods on array variable to find the minimum and maximum elements with in an array.
1963 |
1964 | ```js
1965 | const marks = [50, 20, 70, 60, 45, 30];
1966 |
1967 | function findMin(arr) {
1968 | return Math.min.apply(null, arr);
1969 | }
1970 | function findMax(arr) {
1971 | return Math.max.apply(null, arr);
1972 | }
1973 |
1974 | console.log(findMin(marks)); // 20
1975 | console.log(findMax(marks)); // 70
1976 | ```
1977 |
1978 |
1979 |
1980 |
1983 |
1984 | ## Q. Write a program to find the max values in an array without using Math functions?
1985 |
1986 | **Example:**
1987 |
1988 | ```js
1989 | Input: [50, 20, 70, 60, 45, 30];
1990 | Output:
1991 | Max: 70
1992 | ```
1993 |
1994 |
Answer
1995 |
1996 | ```js
1997 | const marks = [50, 20, 70, 60, 45, 30];
1998 |
1999 | function findMax(arr) {
2000 | let length = arr.length;
2001 | let max = marks[0];
2002 | while (length--) {
2003 | if (arr[length] > max) {
2004 | max = arr[length];
2005 | }
2006 | }
2007 | return max;
2008 | }
2009 |
2010 | console.log(findMax(marks)); // 70
2011 | ```
2012 |
2013 |
2014 |
2015 |
2018 |
2019 | ## Q. Check if object is empty or not using javaScript?
2020 |
2021 | **Example:**
2022 |
2023 | ```js
2024 | Input:
2025 | const obj = {};
2026 | console.log(isEmpty(obj)); // true
2027 | ```
2028 |
2029 |
Answer
2030 |
2031 | ```js
2032 | function isEmpty(obj) {
2033 | return Object.keys(obj).length === 0;
2034 | }
2035 |
2036 | const obj = {};
2037 | console.log(isEmpty(obj));
2038 | ```
2039 |
2040 | **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-isempty-b7n04b?file=/src/index.js)**
2041 |
2042 |
2043 |
2044 |
2047 |
2048 | ## Q. Write a function to validate an email using regular expression?
2049 |
2050 | **Example:**
2051 |
2052 | ```js
2053 | Input: 'pradeep.vwa@gmail.com'
2054 | Output: true
2055 | ```
2056 |
2057 |
Answer
2058 |
2059 | ```js
2060 | function validateEmail(email) {
2061 | const re = /\S+@\S+\.\S+/;
2062 | return re.test(email);
2063 | }
2064 |
2065 | console.log(validateEmail("pradeep.vwa@gmail.com")); // true
2066 | ```
2067 |
2068 | **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-validateemail-wfopym?file=/src/index.js)**
2069 |
2070 |
2071 |
2072 |
2075 |
2076 | ## Q. Use RegEx to test password strength in JavaScript?
2077 |
2078 | **Example:**
2079 |
2080 | ```js
2081 | Input: 'Pq5*@a{J'
2082 | Output: 'PASS'
2083 | ```
2084 |
2085 |
Answer
2086 |
2087 | ```js
2088 | let newPassword = "Pq5*@a{J";
2089 | const regularExpression = new RegExp(
2090 | "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})"
2091 | );
2092 |
2093 | if (!regularExpression.test(newPassword)) {
2094 | alert("Password should contain atleast one number and one special character !");
2095 | } else {
2096 | console.log("PASS");
2097 | }
2098 |
2099 | // Output
2100 | PASS
2101 | ```
2102 |
2103 | | RegEx | Description |
2104 | | ---------------- |--------------|
2105 | | ^ | The password string will start this way |
2106 | | (?=.\*[a-z]) | The string must contain at least 1 lowercase alphabetical character |
2107 | | (?=.\*[A-Z]) | The string must contain at least 1 uppercase alphabetical character |
2108 | | (?=.\*[0-9]) | The string must contain at least 1 numeric character |
2109 | | (?=.[!@#\$%\^&]) | The string must contain at least one special character, but we are escaping reserved RegEx characters to avoid conflict |
2110 | | (?=.{8,}) | The string must be eight characters or longer |
2111 |
2112 | **⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/js-cp-password-strength-cxl8xy)**
2113 |
2114 |
2115 |
2116 |
2119 |
2120 | ## Q. Write a program to count the number of occurrences of character given a string as input?
2121 |
2122 | **Example:**
2123 |
2124 | ```js
2125 | Input: 'Hello'
2126 | Output:
2127 | h: 1
2128 | e: 1
2129 | l: 2
2130 | o: 1
2131 | ```
2132 |
2133 |
Answer
2134 |
2135 | ```js
2136 | function countCharacters(str) {
2137 | return str.replace(/ /g, "").toLowerCase().split("").reduce((result, key) => {
2138 | if (key in result) {
2139 | result[key]++;
2140 | } else {
2141 | result[key] = 1;
2142 | }
2143 | return result;
2144 | }, {});
2145 | }
2146 |
2147 | console.log(countCharacters("Hello"));
2148 | ```
2149 |
2150 |
2151 |
2152 |
2155 |
2156 | ## Q. Write a function that return the number of occurrences of a character in paragraph?
2157 |
2158 | **Example:**
2159 |
2160 | ```js
2161 | Input: 'the brown fox jumps over the lazy dog'
2162 | Key: 'o'
2163 | Output: 4
2164 | ```
2165 |
2166 |
Answer
2167 |
2168 | ```js
2169 | function charCount(str, searchChar) {
2170 | let count = 0;
2171 | if (str) {
2172 | let stripStr = str.replace(/ /g, "").toLowerCase(); //remove spaces and covert to lowercase
2173 | for (let chr of stripStr) {
2174 | if (chr === searchChar) {
2175 | count++;
2176 | }
2177 | }
2178 | }
2179 | return count;
2180 | }
2181 | console.log(charCount("the brown fox jumps over the lazy dog", "o"));
2182 | ```
2183 |
2184 |
2185 |
2186 |
2189 |
2190 | ## Q. Write a recursive and non-recursive Factorial function?
2191 |
2192 | **Example:**
2193 |
2194 | ```js
2195 | Input: 5
2196 | Output: 120
2197 | ```
2198 |
2199 |
Answer
2200 |
2201 | ```js
2202 | // Recursive Method
2203 | function recursiveFactorial(n) {
2204 | if (n < 1) {
2205 | throw Error("Value of N has to be greater then 1");
2206 | }
2207 | if (n === 1) {
2208 | return 1;
2209 | } else {
2210 | return n * recursiveFactorial(n - 1);
2211 | }
2212 | }
2213 |
2214 | console.log(recursiveFactorial(5));
2215 |
2216 | // Non-Recursive Method
2217 | function factorial(n) {
2218 | if (n < 1) {
2219 | throw Error("Value of N has to be greater then 1");
2220 | }
2221 | if (n === 1) {
2222 | return 1;
2223 | }
2224 | let result = 1;
2225 | for (let i = 1; i <= n; i++) {
2226 | result = result * i;
2227 | }
2228 | return result;
2229 | }
2230 |
2231 | console.log(factorial(5));
2232 | ```
2233 |
2234 |
2235 |
2236 |
2239 |
2240 | ## Q. Write a recursive and non recursive fibonacci-sequence?
2241 |
2242 | **Example:**
2243 |
2244 | ```js
2245 | Input: 8
2246 | Output: 34
2247 | ```
2248 |
2249 |
Answer
2250 |
2251 | ```js
2252 | // 1, 1, 2, 3, 5, 8, 13, 21, 34
2253 | // Recursive Method
2254 | function recursiveFibonacci(num) {
2255 | if (num <= 1) {
2256 | return 1;
2257 | } else {
2258 | return recursiveFibonacci(num - 1) + recursiveFibonacci(num - 2);
2259 | }
2260 | }
2261 |
2262 | console.log(recursiveFibonacci(8));
2263 |
2264 | // Non-Recursive Method
2265 | function fibonnaci(num) {
2266 | let a = 1, b = 0, temp;
2267 | while (num >= 0) {
2268 | temp = a;
2269 | a = a + b;
2270 | b = temp;
2271 | num--;
2272 | }
2273 | return b;
2274 | }
2275 |
2276 | console.log(fibonnaci(7));
2277 |
2278 | // Memoization Method
2279 | function fibonnaci(num, memo = {}) {
2280 | if (num in memo) {
2281 | return memo[num];
2282 | }
2283 | if (num <= 1) {
2284 | return 1;
2285 | }
2286 | return (memo[num] = fibonnaci(num - 1, memo) + fibonnaci(num - 2, memo));
2287 | }
2288 |
2289 | console.log(fibonnaci(5)); // 8
2290 | ```
2291 |
2292 |
2293 |
2294 |
2297 |
2298 | ## Q. Write a function to reverse the number?
2299 |
2300 | **Example:**
2301 |
2302 | ```js
2303 | Input: 12345
2304 | Output: 54321
2305 | ```
2306 |
2307 |
Answer
2308 |
2309 | ```js
2310 | function reverse(num) {
2311 | let result = 0;
2312 | while (num != 0) {
2313 | result = result * 10;
2314 | result = result + (num % 10);
2315 | num = Math.floor(num / 10);
2316 | }
2317 | return result;
2318 | }
2319 |
2320 | console.log(reverse(12345));
2321 | ```
2322 |
2323 |
2324 |
2325 |
2328 |
2329 | ## Q. Write a function to reverse an array?
2330 |
2331 | **Example:**
2332 |
2333 | ```js
2334 | Input: [10, 20, 30, 40, 50]
2335 | Output: [50, 40, 30, 20, 10]
2336 | ```
2337 |
2338 |
Answer
2339 |
2340 | ```js
2341 | let a = [10, 20, 30, 40, 50];
2342 |
2343 | //Approach 1:
2344 | console.log(a.reverse());
2345 |
2346 | //Approach 2:
2347 | let reverse = a.reduce((prev, current) => {
2348 | prev.unshift(current);
2349 | return prev;
2350 | }, []);
2351 |
2352 | console.log(reverse);
2353 | ```
2354 |
2355 |
2356 |
2357 |
2360 |
2361 | ## Q. Get top N from array
2362 |
2363 | **Example:**
2364 |
2365 | ```js
2366 | Input: [1, 8, 3, 4, 5]
2367 | Key: 2
2368 | Output: [5, 8]
2369 | ```
2370 |
2371 |
Answer
2372 |
2373 | ```js
2374 | function topN(arr, num) {
2375 | let sorted = arr.sort((a, b) => a - b);
2376 | return sorted.slice(sorted.length - num, sorted.length);
2377 | }
2378 |
2379 | console.log(topN([1, 8, 3, 4, 5], 2)); // [5,8]
2380 | ```
2381 |
2382 |
2383 |
2384 |
2387 |
2388 | ## Q. Get the consecutive 1\'s in binary?
2389 |
2390 | **Example:**
2391 |
2392 | ```js
2393 | Input: 7
2394 | Output: 3
2395 |
2396 | Input: 5
2397 | Output: 1
2398 |
2399 | Input: 13
2400 | Output: 2
2401 | ```
2402 |
2403 |
Answer
2404 |
2405 | ```js
2406 | function consecutiveOne(num) {
2407 | let binaryArray = num.toString(2);
2408 |
2409 | let maxOccurence = 0, occurence = 0;
2410 | for (let val of binaryArray) {
2411 | if (val === "1") {
2412 | occurence += 1;
2413 | maxOccurence = Math.max(maxOccurence, occurence);
2414 | } else {
2415 | occurence = 0;
2416 | }
2417 | }
2418 | return maxOccurence;
2419 | }
2420 |
2421 | console.log(consecutiveOne(7)); // 3
2422 |
2423 | // 13 => 1101 = 2
2424 | // 5 => 101 = 1
2425 | // 7 => 111 = 3
2426 | ```
2427 |
2428 |
2429 |
2430 |
2433 |
2434 | ## Q. Write a program to merge sorted array and sort it?
2435 |
2436 | **Example:**
2437 |
2438 | ```js
2439 | Input: [1, 2, 3, 4, 5, 6], [0, 3, 4, 7]
2440 | Output: [0, 1, 2, 3, 4, 5, 6, 7]
2441 | ```
2442 |
2443 |
Answer
2444 |
2445 | ```js
2446 | function mergeSortedArray(arr1, arr2) {
2447 | return [...new Set(arr1.concat(arr2))].sort((a, b) => a - b);
2448 | }
2449 |
2450 | console.log(mergeSortedArray([1, 2, 3, 4, 5, 6], [0, 3, 4, 7])); // [0, 1, 2, 3, 4, 5, 6, 7]
2451 | ```
2452 |
2453 |
2454 |
2455 |
2458 |
2459 | ## Q. Generate anagram of a given words?
2460 |
2461 | **Example:**
2462 |
2463 | ```js
2464 | Input: ["map", "art", "how", "rat", "tar", "who", "pam", "shoop"]
2465 |
2466 | Output:
2467 | {
2468 | amp: [ 'map', 'pam' ],
2469 | art: [ 'art', 'rat', 'tar' ],
2470 | how: [ 'how', 'who' ],
2471 | hoops: [ 'shoop' ]
2472 | }
2473 | ```
2474 |
2475 |
Answer
2476 |
2477 | ```js
2478 | const alphabetize = (word) => word.split("").sort().join("");
2479 |
2480 | function groupAnagram(wordsArr) {
2481 | return wordsArr.reduce((p, c) => {
2482 | const sortedWord = alphabetize(c);
2483 | if (sortedWord in p) {
2484 | p[sortedWord].push(c);
2485 | } else {
2486 | p[sortedWord] = [c];
2487 | }
2488 | return p;
2489 | }, {});
2490 | }
2491 |
2492 | console.log(groupAnagram(["map", "art", "how", "rat", "tar", "who", "pam", "shoop"]));
2493 | ```
2494 |
2495 |
2496 |
2497 |
2500 |
2501 | ## Q. Write a program to transform array of objects to array?
2502 |
2503 | **Example:**
2504 |
2505 | ```js
2506 | Input:
2507 | [
2508 | { vid: "aaa", san: 12 },
2509 | { vid: "aaa", san: 18 },
2510 | { vid: "aaa", san: 2 },
2511 | { vid: "bbb", san: 33 },
2512 | { vid: "bbb", san: 44 },
2513 | { vid: "aaa", san: 100 },
2514 | ]
2515 |
2516 | Output:
2517 | [
2518 | { vid: 'aaa', san: [ 12, 18, 2, 100 ] },
2519 | { vid: 'bbb', san: [ 33, 44 ] }
2520 | ]
2521 | ```
2522 |
2523 |
Answer
2524 |
2525 | ```js
2526 | let data = [
2527 | { vid: "aaa", san: 12 },
2528 | { vid: "aaa", san: 18 },
2529 | { vid: "aaa", san: 2 },
2530 | { vid: "bbb", san: 33 },
2531 | { vid: "bbb", san: 44 },
2532 | { vid: "aaa", san: 100 },
2533 | ];
2534 |
2535 | let newData = data.reduce((acc, item) => {
2536 | acc[item.vid] = acc[item.vid] || { vid: item.vid, san: [] };
2537 | acc[item.vid]["san"].push(item.san);
2538 | return acc;
2539 | }, {});
2540 |
2541 | console.log(Object.keys(newData).map((key) => newData[key]));
2542 | ```
2543 |
2544 |
2545 |
2546 |
2549 |
2550 | ## Q. Create a private variable or private method in object?
2551 |
2552 |
Answer
2553 |
2554 | ```js
2555 | let obj = (function () {
2556 | function getPrivateFunction() {
2557 | console.log("this is private function");
2558 | }
2559 | let p = "You are accessing private variable";
2560 | return {
2561 | getPrivateProperty: () => {
2562 | console.log(p);
2563 | },
2564 | callPrivateFunction: getPrivateFunction,
2565 | };
2566 | })();
2567 |
2568 | obj.getPrivateValue(); // You are accessing private variable
2569 | console.log("p" in obj); // false
2570 | obj.callPrivateFunction(); // this is private function
2571 | ```
2572 |
2573 |
2574 |
2575 |
2578 |
2579 | ## Q. Write a program to flatten only Array not objects?
2580 |
2581 | **Example:**
2582 |
2583 | ```js
2584 | Input: [1, { a: [2, [3]] }, 4, [5, [6]], [[7, ["hi"]], 8, 9], 10];
2585 |
2586 | Output: [1, { a: [2, [3]]}, 4, 5, 6, 7, "hi", 8, 9, 10]
2587 | ```
2588 |
2589 |
Answer
2590 |
2591 | ```js
2592 | function flatten(arr, result = []) {
2593 | arr.forEach((val) => {
2594 | if (Array.isArray(val)) {
2595 | flatten(val, result);
2596 | } else {
2597 | result.push(val);
2598 | }
2599 | });
2600 | return result;
2601 | }
2602 |
2603 | let input = [1, { a: [2, [3]] }, 4, [5, [6]], [[7, ["hi"]], 8, 9], 10];
2604 |
2605 | console.log(flatten(input)); // [1, { a: [2, [3]]}, 4, 5, 6, 7, "hi", 8, 9, 10]
2606 | ```
2607 |
2608 |
2609 |
2610 |
2613 |
2614 | ## Q. Find max difference between two numbers in Array?
2615 |
2616 | **Example:**
2617 |
2618 | ```js
2619 | Input: [ -10, 4, -9, -5 ];
2620 | Output: -10 - 4 => 14
2621 |
2622 | Input: [1, 2, 4]
2623 | Ouput: 4 - 1 => 3
2624 | ```
2625 |
2626 |
Answer
2627 |
2628 | ```js
2629 | function maxDifference(arr) {
2630 | // find the minimum and the maximum element
2631 | let max = Math.max(...arr);
2632 | let min = Math.min(...arr);
2633 |
2634 | return Math.abs(max - min);
2635 | }
2636 |
2637 | const arr = [1, 2, 4];
2638 | console.log(maxDifference(arr)); // 4 - 1 => 3
2639 | ```
2640 |
2641 |
2642 |
2643 |
2646 |
2647 | ## Q. Panagram ? it means all the 26 letters of alphabet are there
2648 |
2649 | **Example:**
2650 |
2651 | ```js
2652 | Input: 'We promptly judged antique ivory buckles for the next prize'
2653 | Output: 'Pangram'
2654 |
2655 | Input: 'We promptly judged antique ivory buckles for the prize'
2656 | Ouput: 'Not Pangram'
2657 | ```
2658 |
2659 |
Answer
2660 |
2661 | ```js
2662 | function panagram(input) {
2663 | if (input == null) {
2664 | // Check for null and undefined
2665 | return false;
2666 | }
2667 |
2668 | if (input.length < 26) {
2669 | // if length is less then 26 then it is not
2670 | return false;
2671 | }
2672 | input = input.replace(/ /g, "").toLowerCase().split("");
2673 | let obj = input.reduce((prev, current) => {
2674 | if (!(current in prev)) {
2675 | prev[current] = current;
2676 | }
2677 | return prev;
2678 | }, {});
2679 | console.log(Object.keys(obj).length === 26 ? "Panagram" : "Not Pangram");
2680 | }
2681 |
2682 | panagram("We promptly judged antique ivory buckles for the next prize"); // Pangram
2683 | panagram("We promptly judged antique ivory buckles for the prize"); // Not Pangram
2684 | ```
2685 |
2686 |
2687 |
2688 |
2691 |
2692 | ## Q. Write a program to convert a number into a Roman Numeral?
2693 |
2694 | **Example:**
2695 |
2696 | ```js
2697 | Input: 3
2698 | Output: III
2699 |
2700 | Input: 10
2701 | Output: X
2702 | ```
2703 |
2704 |
Answer
2705 |
2706 | ```js
2707 | function romanize(num) {
2708 | let lookup = {
2709 | M: 1000,
2710 | CM: 900,
2711 | D: 500,
2712 | CD: 400,
2713 | C: 100,
2714 | XC: 90,
2715 | L: 50,
2716 | XL: 40,
2717 | X: 10,
2718 | IX: 9,
2719 | V: 5,
2720 | IV: 4,
2721 | I: 1,
2722 | };
2723 | let result = "";
2724 | for (let i in lookup) {
2725 | while (num >= lookup[i]) {
2726 | result += i;
2727 | num -= lookup[i];
2728 | }
2729 | }
2730 | return result;
2731 | }
2732 |
2733 | console.log(romanize(3)); // III
2734 | ```
2735 |
2736 |
2737 |
2738 |
2741 |
2742 | ## Q. Write a program to check if parenthesis is malformed or not?
2743 |
2744 | **Example:**
2745 |
2746 | ```js
2747 | Input: "}{{}}"
2748 | Output: false
2749 |
2750 | Input: "{{[]}}"
2751 | Output: true
2752 | ```
2753 |
2754 |
Answer
2755 |
2756 | ```js
2757 | function matchParenthesis(str) {
2758 | let obj = { "{": "}", "(": ")", "[": "]" };
2759 | let result = [];
2760 | for (let s of str) {
2761 | if (s === "{" || s === "(" || s === "[") {
2762 | // All opening brackets
2763 | result.push(s);
2764 | } else {
2765 | if (result.length > 0) {
2766 | let lastValue = result.pop(); // pop the last value and compare with key
2767 | if (obj[lastValue] !== s) {
2768 | // if it is not same then it is not formated properly
2769 | return false;
2770 | }
2771 | } else {
2772 | return false; // empty array, there is nothing to pop. so it is not formated properly
2773 | }
2774 | }
2775 | }
2776 | return result.length === 0;
2777 | }
2778 |
2779 | console.log(matchParenthesis("}{{}}")); // false
2780 | console.log(matchParenthesis("{{[]}}")); // true
2781 | ```
2782 |
2783 |
2784 |
2785 |
2788 |
2789 | ## Q. Create Custom Event Emitter class?
2790 |
2791 | **Example:**
2792 |
2793 | ```js
2794 | Output:
2795 | 'Custom event called with argument: a,b,[object Object]'
2796 | 'Custom event called without argument'
2797 | ```
2798 |
2799 |
Answer
2800 |
2801 | ```js
2802 | class EventEmitter {
2803 | constructor() {
2804 | this.holder = {};
2805 | }
2806 |
2807 | on(eventName, fn) {
2808 | if (eventName && typeof fn === "function") {
2809 | this.holder[eventName] = this.holder[eventName] || [];
2810 | this.holder[eventName].push(fn);
2811 | }
2812 | }
2813 |
2814 | emit(eventName, ...args) {
2815 | let eventColl = this.holder[eventName];
2816 | if (eventColl) {
2817 | eventColl.forEach((callback) => callback(args));
2818 | }
2819 | }
2820 | }
2821 |
2822 | let e = new EventEmitter();
2823 | e.on("myCustomEvent", function (args) {
2824 | console.log(`Custom event called with arguments: ${args}`);
2825 | });
2826 | e.on("myCustomEvent", function () {
2827 | console.log(`Custom event called without argument`);
2828 | });
2829 |
2830 | e.emit("myCustomEvent", ["a", "b"], { firstName: "Umesh", lastName: "Gohil" });
2831 | ```
2832 |
2833 |
2834 |
2835 |
2838 |
2839 | ## Q. Write a program to move all zeroes to end?
2840 |
2841 | **Example:**
2842 |
2843 | ```js
2844 | Input: [1, 2, 0, 4, 3, 0, 5, 0]
2845 | Output: [1, 2, 4, 3, 5, 0, 0, 0]
2846 | ```
2847 |
2848 |
Answer
2849 |
2850 | ```js
2851 | const moveZeroToEnd = (arr) => {
2852 | for (let i = 0, j = 0; j < arr.length; j++) {
2853 | if (arr[j] !== 0) {
2854 | if (i < j) {
2855 | [arr[i], arr[j]] = [arr[j], arr[i]]; // swap i and j
2856 | }
2857 | i++;
2858 | }
2859 | }
2860 | return arr;
2861 | };
2862 |
2863 | console.log(moveZeroToEnd([1, 2, 0, 4, 3, 0, 5, 0]));
2864 | ```
2865 |
2866 |
2867 |
2868 |
2871 |
2872 | ## Q. Decode message in matrix [diagional down right, diagional up right]
2873 |
2874 | **Example:**
2875 |
2876 | ```js
2877 | Input:
2878 | [
2879 | ["I", "B", "C", "A", "L", "K", "A"],
2880 | ["D", "R", "F", "C", "A", "E", "A"],
2881 | ["G", "H", "O", "E", "L", "A", "D"],
2882 | ["G", "H", "O", "E", "L", "A", "D"],
2883 | ]
2884 |
2885 | Output:
2886 | 'IROELEA'
2887 | ```
2888 |
2889 |
Answer
2890 |
2891 | ```js
2892 | const decodeMessage = (mat) => {
2893 | // check if matrix is null or empty
2894 | if (mat == null || mat.length === 0) {
2895 | return "";
2896 | }
2897 | let x = mat.length - 1;
2898 | let y = mat[0].length - 1;
2899 | let message = "";
2900 | let decode = (mat, i = 0, j = 0, direction = "DOWN") => {
2901 | message += mat[i][j];
2902 |
2903 | if (i === x) {
2904 | direction = "UP";
2905 | }
2906 |
2907 | if (direction === "DOWN") {
2908 | i++;
2909 | } else {
2910 | i--;
2911 | }
2912 |
2913 | if (j === y) {
2914 | return;
2915 | }
2916 |
2917 | j++;
2918 | decode(mat, i, j, direction);
2919 | };
2920 | decode(mat);
2921 | return message;
2922 | };
2923 |
2924 | let mat = [
2925 | ["I", "B", "C", "A", "L", "K", "A"],
2926 | ["D", "R", "F", "C", "A", "E", "A"],
2927 | ["G", "H", "O", "E", "L", "A", "D"],
2928 | ["G", "H", "O", "E", "L", "A", "D"],
2929 | ];
2930 |
2931 | console.log(decodeMessage(mat)); // IROELEA
2932 | ```
2933 |
2934 |
2935 |
2936 |
2939 |
2940 | ## Q. Find a pair in array, whose sum is equal to given number?
2941 |
2942 | **Example:**
2943 |
2944 | ```js
2945 | Input: [6, 4, 3, 8], Sum = 8
2946 | Output: false
2947 |
2948 | Input: [1, 2, 4, 4], Sum = 8
2949 | Output: true
2950 | ```
2951 |
2952 |
Answer
2953 |
2954 | ```js
2955 | const hasPairSum = (arr, sum) => {
2956 | let difference = {};
2957 | let hasPair = false;
2958 |
2959 | arr.forEach((item) => {
2960 | let diff = sum - item;
2961 | if (!difference[diff]) {
2962 | difference[item] = true;
2963 | } else {
2964 | hasPair = true;
2965 | }
2966 | });
2967 | return hasPair;
2968 | };
2969 |
2970 | console.log(hasPairSum([6, 4, 3, 8], 8)); // false
2971 | console.log(hasPairSum([1, 2, 4, 4], 8)); // true
2972 | ```
2973 |
2974 |
2975 |
2976 |
2979 |
2980 | ## Q. Write a Binary Search Program (array should be sorted)?
2981 |
2982 | **Example:**
2983 |
2984 | ```js
2985 | Input: [-1, 10, 22, 35, 48, 56, 67], key = 22
2986 | Output: 2
2987 |
2988 | Input: [-1, 10, 22, 35, 48, 56, 67], key = 27
2989 | Output: -1
2990 | ```
2991 |
2992 |
Answer
2993 |
2994 | ```js
2995 | function binarySearch(arr, val) {
2996 | let startIndex = 0,
2997 | stopIndex = arr.length - 1,
2998 | middleIndex = Math.floor((startIndex + stopIndex) / 2);
2999 |
3000 | while (arr[middleIndex] !== val && startIndex < stopIndex) {
3001 | if (val < arr[middleIndex]) {
3002 | stopIndex = middleIndex - 1;
3003 | } else if (val > arr[middleIndex]) {
3004 | startIndex = middleIndex + 1;
3005 | }
3006 | middleIndex = Math.floor((startIndex + stopIndex) / 2);
3007 | }
3008 |
3009 | return arr[middleIndex] === val ? middleIndex : -1;
3010 | }
3011 |
3012 | console.log(binarySearch([-1, 10, 22, 35, 48, 56, 67], 22)); // 2
3013 | console.log(binarySearch([-1, 10, 22, 35, 48, 56, 67], 27)); // -1
3014 | ```
3015 |
3016 |
3017 |
3018 |
3021 |
3022 | ## Q. Write a function to generate Pascal triangle?
3023 |
3024 | **Example:**
3025 |
3026 | ```js
3027 | Input: 5
3028 |
3029 | Output:
3030 | [ 1 ],
3031 | [ 1, 1 ],
3032 | [ 1, 2, 1 ],
3033 | [ 1, 3, 3, 1 ],
3034 | [ 1, 4, 6, 4, 1 ],
3035 | [ 1, 5, 10, 10, 5, 1 ]
3036 | ```
3037 |
3038 |
Answer
3039 |
3040 | ```js
3041 | function pascalTriangle(n) {
3042 | let last = [1],
3043 | triangle = [last];
3044 | for (let i = 0; i < n; i++) {
3045 | const ls = [0].concat(last),
3046 | rs = last.concat([0]);
3047 | last = rs.map((r, i) => ls[i] + r);
3048 | triangle = triangle.concat([last]);
3049 | }
3050 | return triangle;
3051 | }
3052 |
3053 | console.log(pascalTriangle(5));
3054 | ```
3055 |
3056 |
3057 |
3058 |
3061 |
3062 | ## Q. Remove array element based on object property?
3063 |
3064 | **Example:**
3065 |
3066 | ```js
3067 | Input:
3068 | [
3069 | { field: "id", operator: "eq" },
3070 | { field: "cStatus", operator: "eq" },
3071 | { field: "money", operator: "eq" },
3072 | ]
3073 |
3074 | Key: 'money'
3075 |
3076 | Output:
3077 | [
3078 | { field: 'id', operator: 'eq' },
3079 | { field: 'cStatus', operator: 'eq' }
3080 | ]
3081 | ```
3082 |
3083 |
Answer
3084 |
3085 | ```js
3086 | let myArray = [
3087 | { field: "id", operator: "eq" },
3088 | { field: "cStatus", operator: "eq" },
3089 | { field: "money", operator: "eq" },
3090 | ];
3091 |
3092 | myArray = myArray.filter((obj) => {
3093 | return obj.field !== "money";
3094 | });
3095 |
3096 | console.log(myArray);
3097 | ```
3098 |
3099 |
3100 |
3101 |
3104 |
3105 | ## Q. Write a program to get the value of an object from a specific path?
3106 |
3107 | **Example:**
3108 |
3109 | ```js
3110 | Input:
3111 | {
3112 | user: {
3113 | username: 'Navin Chauhan',
3114 | password: 'Secret'
3115 | },
3116 | rapot: {
3117 | title: 'Storage usage raport',
3118 | goal: 'Remove unused data.'
3119 | }
3120 | };
3121 |
3122 | Key: 'user.username'
3123 |
3124 | Output:
3125 | 'Navin Chauhan'
3126 | ```
3127 |
3128 |
Answer
3129 |
3130 | ```js
3131 | const data = {
3132 | user: {
3133 | username: "Navin Chauhan",
3134 | password: "Secret",
3135 | },
3136 | rapot: {
3137 | title: "Storage usage raport",
3138 | goal: "Remove unused data.",
3139 | },
3140 | };
3141 |
3142 | const path = "user.username";
3143 |
3144 | const getObjectProperty = (object, path) => {
3145 | const parts = path.split(".");
3146 |
3147 | for (let i = 0; i < parts.length; ++i) {
3148 | const key = parts[i];
3149 | object = object[key];
3150 | }
3151 | return object;
3152 | };
3153 |
3154 | console.log(getObjectProperty(data, path));
3155 | ```
3156 |
3157 |
3158 |
3159 |
3162 |
3163 | ## Q. Print all pairs with given sum?
3164 |
3165 | **Example:**
3166 |
3167 | ```js
3168 | Input: [1, 5, 7, -1, 5], sum = 6
3169 | Output: (1, 5) (7, -1) (1, 5)
3170 |
3171 | Input: [2, 5, 17, -1], sum = 7
3172 | Output: (2, 5)
3173 | ```
3174 |
3175 |
Answer
3176 |
3177 | ```js
3178 | function getPairs(arr, sum) {
3179 | // Consider all possible pairs and check
3180 | // their sums
3181 | for (let i = 0; i < arr.length; i++) {
3182 | for (let j = i + 1; j < arr.length; j++) {
3183 | if (arr[i] + arr[j] === sum) {
3184 | console.log(arr[i] + ", " + arr[j]);
3185 | }
3186 | }
3187 | }
3188 | }
3189 |
3190 | getPairs([1, 5, 7, -1, 5], 6);
3191 |
3192 | // Output
3193 | // (1, 5)
3194 | // (1, 5)
3195 | // (7, -1)
3196 | ```
3197 |
3198 |
3199 |
3200 |
3203 |
3204 | ## Q. Write a function to find out duplicate words in a given string?
3205 |
3206 | **Example:**
3207 |
3208 | ```js
3209 | Input:
3210 | "big black bug bit a big black dog on his big black nose"
3211 |
3212 | Output:
3213 | "big black"
3214 | ```
3215 |
3216 |
Answer
3217 |
3218 | ```js
3219 | const str = "big black bug bit a big black dog on his big black nose";
3220 |
3221 | const findDuplicateWords = (str) => {
3222 | const strArr = str.split(" ");
3223 | const res = [];
3224 | for (let i = 0; i < strArr.length; i++) {
3225 | if (strArr.indexOf(strArr[i]) !== strArr.lastIndexOf(strArr[i])) {
3226 | if (!res.includes(strArr[i])) {
3227 | res.push(strArr[i]);
3228 | }
3229 | }
3230 | }
3231 | return res.join(" ");
3232 | };
3233 |
3234 | console.log(findDuplicateWords(str));
3235 | ```
3236 |
3237 |
3238 |
3239 |
3242 |
--------------------------------------------------------------------------------