forked from priya42bagde/JavaScriptCodingInterviewQuestions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs codes.docx
3261 lines (3041 loc) · 129 KB
/
js codes.docx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
For JavaScript Theorytical questions: "https://github.com/sudheerj/javascript-interview-questions"
For Reactjs theory questions: https://github.com/sudheerj/reactjs-interview-questions/tree/master/.github/workflows
For Google, Facebook, Microsoft coding challenges: https://youtube.com/c/KevinNaughtonJr
Jest: https://github.com/sapegin/jest-cheat-sheet
https://learnersbucket.com/javascript-sde-cheat-sheet/
https://javascript.info/
https://frontenddeveloperinterview.netlify.app/
================================================================================================================================================================================
Code 1: Remove Duplicate characters from String
function removeDuplicateCharacters() {
var string='priya riya supriya'
let result= string.split('').filter((item, index, arr)=> {
return arr.indexOf(item) == index;
}).join('');
return result;
}
console.log(removeDuplicateCharacters());
================================================================================================================================================================================
Code 2: Remove Duplicate characters from array of element and find the count of an elements using set object
var arr = [55, 44, 55,67,67,67,67,8,8,8,8,8,65,1,2,3,3,34,5];
var unique = [...new Set(arr)]
console.log(unique) //output: [55, 44, 67, 8, 65, 1, 2, 3, 34, 5]
console.log(unique.length) //output: 10
================================================================================================================================================================================
Code 3: Remove Duplicate characters from array of element using filter
var myArray = ['a', 1, 'a', 2, '1'];
var unique = myArray.filter((value, index, arr) => arr.indexOf(value) === index);
================================================================================================================================================================================
Code 4:String reverse without reversing of individual words (Array of elements can be reverse with reverse() method but for string it is won't possible so required to split
and then join().
function removeDuplicates(){
var string ="India is my country"
let result = string.split('').reverse().join('').split(' ').reverse().join(' ')
return result
}
console.log(removeDuplicates())
output = "aidnI si ym yrtnuoc"
================================================================================================================================================================================
Code 5:String reverse with reversing of individual words
function withoutReverse(){
var string ="India is my country"
let result = string.split('').reverse().join('')
return result
}
console.log(withoutReverse())
output = "yrtnuoc ym si aidnI"
================================================================================================================================================================================
Code 6:String reverse without using inbult function
function Reverse(){
var string ="India is my country";
var result="";
for( var i=string.length-1; i>=0 ; i-- ) {
result=result+string[i] }
return result
}
console.log(Reverse())
output = "yrtnuoc ym si aidnI"
================================================================================================================================================================================
Code 7: Find factorial of user input number
const number = parseInt(prompt('Enter a positive integer: '));
if (number < 0) { console.log('Error! Factorial for negative number does not exist.')}
else if (number === 0) { console.log(`The factorial is 1.`)}
else {
let fact = 1;
for (i = 1; i <= number; i++) {
fact *= i;
}
console.log(`The factorial is ${fact}.`);
}
================================================================================================================================================================================
Code 8:Anagram
function checkStringsAnagram() {
var a="Army";
var b="Mary"
let str1 = a.toLowerCase().split('').sort().join('');
let str2 = b.toLowerCase().split('').sort().join('');
if(str1 === str2){
console.log("True");
}
else {
console.log("False");
}
}
================================================================================================================================================================================
Code 9: Swapping of 2 numbers with third variable
let a=10;
let b=20;
let c;
c=a;
a=b;
b=c;
console.log (a,b,c)
================================================================================================================================================================================
Code 10: Swapping of 2 numbers without third variable
let a=10;
let b=20;
a=a+b //30
b=a-b //10
a=a-b //20
console.log (a,b)
================================================================================================================================================================================
Code 11: To check the string or number is palindrome or not( ex: 121,madam,anna) using reverse method
function checkPalindrome(){
const string = "anmna"
let arr= string.split('').reverse().join('')
//console.log(arr)
if (string==arr){
console.log("Palindrome")
}
else{
console.log("Not Palindrome")
}
}
checkPalindrome()
================================================================================================================================================================================
Code 12: To check the string or number is palindrome or not( ex: 121,madam,anna) using diving length by 2 and then comparing
function checkPalindrome(){
const string = "12321"
let len = string.length;
for (i=0; i<len/2;i++){
if (string[i]!==string[len-1-i]){
console.log("Not Palindrome")
}
else{
console.log(" Palindrome")
}
}
}
checkPalindrome()
================================================================================================================================================================================
Code 13: To find longest word from a string using (for of) /*for(var i=0; i>=num; i++) means iterate by indexing*/ /*for (var word of words) means iterate by an elements not
by indexing*/
function longestWord(){
let string = "supriya is a masooooom good girl"
var words= string.split(' ')
var longest=" "
for(var word of words){
console.log(word)
if (word.length > longest.length)
{
longest=word;
}
}
return longest.length
}
longestWord()
---------------------------
function longestWord(){
let string = "supriya is a hahahahaha good girl"
var arr= string.split(' ')
var longest=" "
for(var i=0; i<arr.length; i++){
if (arr[i].length > longest.length)
{
longest=arr[i];
}
}
return longest
}
console.log(longestWord())
================================================================================================================================================================================
Code 14: To find longest word from a string using functions
function findLongestWord() {
var str = "Priya is a goog girl and having hardworking skill"
var longestWord = str.split(' ').sort((a, b) => {return b.length - a.length }); //in desc order //from greater to smallest word
console.log(longestWord[0]);
console.log(longestWord[0].length);
}
findLongestWord();
================================================================================================================================================================================
Code 15: To find longest word from a string using custom code
function longest() {
var str ="Priya is a good girl and having hardworking skills"
var words = str.split(' ');
var longest = '';
for (var i = 0; i < words.length; i++) {
if (words[i].length > longest.length) {
longest = words[i];
}
}
console.log(longest)
return longest;
}
longest();
================================================================================================================================================================================
Code 16: To find longest common string from array of strings
function longestCommonString(){
array=["go","google","gosh"]
var arr = array.sort()
var i=0;
while(arr[0].length>0 && arr[0].charAt(i)===arr[arr.length-1].charAt(i)){
i++;
}
console.log(arr[0].substring(0,i)) // "go"
return arr[0].substring(0,i)
}
longestCommonString()
================================================================================================================================================================================
Code 17: To find vowels and its count in a given string
function vowelCounts(){
vowels=["a","i","e","o","u"]
var str ="priya"
count=0;
for(var letter of str.toLowerCase())
{
if(vowels.includes(letter))
{
count++;
console.log(letter)
}
}
console.log(count)
return count
}
vowelCounts()
================================================================================================================================================================================
Code 18:To find character occurance fro the string
function characterOccurance(str,letter){
let count =0;
for(var i=0; i<str.length-1; i++){
if(str.charAt(i)===letter)
{
count++
}
}
console.log(count)
return count
}
characterOccurance("priyapri", "p")
================================================================================================================================================================================
Code 19: To find a first pair whose sum is zero
function getSumPairZero(array)
{
for(let number of array)
{
for(let i=1; i<array.length; i++)
{
if(number+array[i]===0)
{
return [number, array[i]]
}
}
}
}
const result = getSumPairZero([-5,-4,-3,-2,-1,0,1,2,3,4,5])
console.log(result)
------------------------------------------------
function getSumPairZero(array)
{
for(let j=0; j<array.length;j++)
{
for(let i=1; i<array.length; i++)
{
if(array[j]+array[i]===0)
{
return [array[j], array[i]]
}
}
}
}
const result = getSumPairZero([-5,-4,-3,-2,-1,0,1,2,3,4,5])
console.log(result)
================================================================================================================================================================================
Code 20: To find a first pair whose sum is zero using indexing //Firstly do a sort here
function getSumPairZero(array)
{
let left = 0;
let right = array.length-1;
while(left<right)
{
sum = array[left]+array[right]
if(sum===0){
return [array[left],array[right]]
}else if(sum>0){
right--;
}else{
left++;
}
}
}
const result = getSumPairZero([-5,-4,-3,-2,-1,0,2,4,6,8])
console.log(result)
================================================================================================================================================================================
Code 21: To find the largest pair of the 2 elements using indexing with unsorted elements
function largestPairSumofTwo(numbers){
const num = numbers.sort((a, b) => b - a);
console.log(num)
return num[0] + num[1];
}
const result = largestPairSumofTwo([9,7,8,4,5,6,1,2,3])
console.log(result)
================================================================================================================================================================================
Code 22: To find the largest pair of the 2 elements using indexing with sorted elements
function largestPairSumofTwo(num){
return num[num.length-1] + num[num.length-2];
}
const result = largestPairSumofTwo([1,2,3,4,5,6,7,8,9])
console.log(result)
================================================================================================================================================================================
Code 23: To find the index of an element from an array
const letters = ['a', 'b', 'c']
const index = letters.indexOf('b')
console.log(index) // `1`
================================================================================================================================================================================
Code 24: Fibonacci Series (0,1,1,2,3,5,8,13....)
function fibonacciSeries(){
const number = parseInt(prompt('Enter the number of terms: '));
let n1 = 0, n2 = 1, nextTerm, arr=[]
arr.push(n1)
arr.push(n2)
for (let i = 1; i <= number; i++)
{
console.log(n1);
nextTerm = n1 + n2;
n1 = n2;
n2 = nextTerm;
arr.push(nextTerm)
}
return arr
}
console.log(fibonacciSeries())
================================================================================================================================================================================
Code 25: Fibonacci Series (0,1,1,2,3,5,8,13....) where keeping in array
function listFibonacci(n) {
var arr = [0, 1]
for (var i = 1; i < n; i++)
arr.push(arr[i] + arr[i - 1])
return arr
}
console.log(listFibonacci(4))
================================================================================================================================================================================
Code 26: Finding a missing elements in an array and then add with existing elements. (-1 means if elements not found then it will return always -1 as per rule)
function missingElement(){
var a = [1,2,5]
var missing = [];
for (var i = 1; i <= 6; i++)
{
if (a.indexOf(i) == -1)
{
missing.push(i);
}
}
console.log(missing) //missing array
console.log(a.concat(missing).sort()); //actual+missing elements
}
missingElement()
================================================================================================================================================================================
Code 27: Find the missing no. in an array
function missing(arr) {
var x = 0;
for (var i = 0; i < arr.length; i++) {
x = x + 1;
if (arr[i] != x) {
return(x); //9
}
}
}
missing([1, 2, 3, 4, 5, 6, 7, 8, 10])
-------------------------------------------
function missing(arr) {
for (var i = 0, x=1; i < arr.length; x++,i++) {
if (arr[i] != x) { //index value comparing with pointer
return x; //9
}
}
}
console.log(missing([1, 2, 3, 4, 5, 6, 7, 8, 10]))
================================================================================================================================================================================
Code 28: Sorting of an string/character
function sorting(arr) {
return arr.sort()
}
console.log(sorting(["d","g","y","e","r","p"]))
================================================================================================================================================================================
Code 29: Sorting of an number
function sorting(arr) {
return arr.sort((a,b)=>{return a-b})
}
console.log(sorting([1,23,34,2,76,78])) //[1, 2, 23, 34, 76, 78]
================================================================================================================================================================================
Code 30: To check if given number is prime or not
function isPrime(num) {
if(num < 2) return false;
for (let k = 2; k < num; k++){
if( num % k == 0){ return false}
}
return true;
}
console.log(isPrime(17)) //true
================================================================================================================================================================================
Code 31: To print all the numbers from 2 to 100
for (let i = 2; i <= 100; i++) {
let flag = 0;
for (let j = 2; j < i; j++) {
if (i % j == 0) {
flag = 1;
break;
}
}
if (i > 1 && flag == 0) {
console.log(i);
}
}
--------------------------------------
for (let i = 2; i <= 100; i++)
{
let flag = 0;
for (let j = 2; j < i; j++) { //2<2 //2<3 //3<4
if (i % j == 0) {
flag = 1;
break;
}
}
if (i > 1 && flag == 0)
{
document.write(i+ "</br>");
}
}
================================================================================================================================================================================
Code 32: To find unique values from 2 arrays and keep into one array.
function uniqueElements(arr1,arr2){
let arr =[...arr1,...arr2];
let array =[...new Set(arr)]
console.log(array)
}
uniqueElements([1,2,3,4,4],[2,3,4,5,6])
================================================================================================================================================================================
Code 33: Find first duplicate element from an array
function firstDuplicate() {
let arr = [1,2,2,5,5];
let data = [];
for (var item of arr) {
if (data[item]) {
return item
} else {
data[item] = item
console.log(data[item])
}
}
return -1
}
console.log(firstDuplicate())
================================================================================================================================================================================
Code 34: Write a program that prints the numbers from 1 to 100. But for multiples of three, print "Fizz" instead of the number, and for the multiples of five, print "Buzz".
For numbers which are multiples of both three and five, print "FizzBuzz"
for (var i=1; i <= 20; i++)
{
if (i % 15 == 0)
console.log("FizzBuzz");
else if (i % 3 == 0)
console.log("Fizz");
else if (i % 5 == 0)
console.log("Buzz");
else
console.log(i);
}
================================================================================================================================================================================
Code 35: Uppercase of each first letter of a words
function upperCaseFirsstLetter(){
var string ="India is my country";
var words = string.toLowerCase().split(" ")
for( var i=0; i<words.length; i++) {
words[i]=words[i][0].toUpperCase() + words[i].slice(1) //slice is used here to give all the letters except first letter.
}
return words.join(" ")
}
console.log(upperCaseFirsstLetter())
================================================================================================================================================================================
Code 36: Uppercase of each first letter of a words using map function
function upperCaseFirsstLetter(){
var string ="India is my country";
var words = string.toLowerCase().split(" ").map((ele)=>{
return ele[0].toUpperCase() + ele.slice(1)
})
return words.join(" ")
}
console.log(upperCaseFirsstLetter())
================================================================================================================================================================================
Code 37: To check ending of the string with given character/s using inbuild function
function confirmEnding(str,target){
return str.endsWith(target) //true
}
console.log(confirmEnding("priya","a"))
===============================================================================================================================================================================
Code 38: To check ending of the string with given character/s using custom
function confirmEnding(str,target){
return str.substr(-target.length)===target
}
console.log(confirmEnding("priya","a"))
===============================================================================================================================================================================
Code 39: To find the largest elements fro the 2 dimensional array
function largestFromArray(arr){
var max=[];
for(var i=0; i<arr.length;i++){
var tempMax =arr[i][0] //first elements of the 4 internal arrays i,e(1,5,45,89
for(var j=0; j<arr[i].length; j++){
var currElement = arr[i][j];
if(currElement>=tempMax){
tempMax = currElement
}
}
max.push(tempMax)
}
console.log(max)
return max;
}
largestFromArray([[1,2,3,4],[5,6,7,9],[45,76,2,1],[89,90,87,9]])
================================================================================================================================================================================
Code 40: To find the largest elements fro the 2 dimensional array in another way
function largestFromArray(arr){
var max=[0,0,0,0];
for(var i=0; i<arr.length;i++){
for(var j=0; j<arr[i].length; j++)
{
if(arr[i][j]>=max[i]){
max[i] = arr[i][j]
}
}
}
console.log(max)
return max;
}
largestFromArray([[1,2,3,4],[5,6,7,9],[45,76,2,1],[89,90,87,9]])
================================================================================================================================================================================
Code 41: Print string n times using inbuilt function
function repeatStrinNumTimes(str, num){
if (num<1) return ""
return str.repeat(num)
}
console.log(repeatStrinNumTimes("priya",3))
================================================================================================================================================================================
Code 42: Print string n times in custom way
function repeatStrinNumTimes(str, num){
var final="";
if(num<0) return ""
for(var i=0; i<num;i++)
{
final=final+str
}
return final
}
console.log(repeatStrinNumTimes("priya",3))
================================================================================================================================================================================
Code 43:Print string n times in custom way
function repeatStrinNumTimes(str, num){
if(num<0) return ""
if(num===1) return str
return str+ repeatStrinNumTimes(str, num-1)
}
console.log(repeatStrinNumTimes("priya",3))
================================================================================================================================================================================
Code 44: Truncate the string
function truncateString(str, num){
if(num<=3) return str.slice(0,num)
return str.slice(0,num-3)+"..." //retuen only 4 digits thats why subtracted from 3
}
console.log(truncateString("priyabagde",2)) //pr
console.log(truncateString("priyabagde",4)) //p... //retuen only 4 digits
================================================================================================================================================================================
Code 45: Converting one dimensional array into n dimensional array using slice
function chunkArrayInGroup(arr, size){
var group=[]
while(arr.length>0){
group.push(arr.slice(0, size))
arr = arr.slice(size)
}
return group
}
console.log (chunkArrayInGroup(['a','b','c','d'],2)) //[["a", "b"], ["c", "d"]]
================================================================================================================================================================================
Code 46: Converting one dimensional array into n dimensional array using splice
function chunkArrayInGroup(arr, size){
var group=[]
while(arr.length>0){
group.push(arr.splice(0, size))
}
return group
}
console.log (chunkArrayInGroup(['a','b','c','d'],2)) //[["a", "b"], ["c", "d"]]
================================================================================================================================================================================
Code 47: To find only truthy values
function removeFalseValue(arr){
var trueth = []
for (var item of arr){
if(item){
trueth.push(item)
}
}
return trueth
}
console.log(removeFalseValue(["priya", 0 ,"", false, null,undefined, "ate", Nan ,9 ])) //["priya","ate",9]
================================================================================================================================================================================
Code 49: To find only truthy values using filter
function removeFalseValue(arr){
return arr.filter((item)=>{
return item})
}
console.log(removeFalseValue(["priya", 0 ,"", false, null,undefined, "ate", 9 ]))
================================================================================================================================================================================
Code 50: Checking all letters of second words should present in first word, in the same order using include function
function characterPresent(arr){
var first = arr[0].toLowerCase()
var second = arr[1].toLowerCase()
for (var letter of second){
if(!first.includes(letter)){
return false
}
}
return true
}
console.log(characterPresent(["hello","hey"]))
================================================================================================================================================================================
Code 51: Checking all letters of second words should present in first word, in the same order using indexOf without indexing i.e for-of loop
function characterPresent(arr){
var first = arr[0].toLowerCase()
var second = arr[1].toLowerCase()
for (var letter of second){
if(first.indexOf(letter)== -1){ //-1 means not found in array
return false
}
}
return true
}
console.log(characterPresent(["hello","he"]))
---------------------------------------------------
function characterPresent(arr){
var first = arr[0].toLowerCase()
var second = arr[1].toLowerCase()
for (var i=0; i<second.length; i++){
if(!first.includes(second[i])){ //-1 means not found in array
return false
}
}
return true
}
console.log(characterPresent(["hello","he"]))
================================================================================================================================================================================
Code 52: Checking all letters of second words should present in first word, in the same order using indexOf with indexing
function characterPresent(arr){
var first = arr[0].toLowerCase()
var second = arr[1].toLowerCase()
for (var i=0; i<second.length; i++){
if(first.indexOf(second)== -1){ //-1 means not found in array
return false
}
}
return true
}
console.log(characterPresent(["hello","he"]))
================================================================================================================================================================================
Code 53: Unique values only from 2 arrays
function diffArrayElement(arr1, arr2){
var result =[]
for(var i=0; i<arr1.length; i++){
if(arr2.indexOf(arr1[i]) === -1){
result.push(arr1[i])
}
}
for(var j=0; j<arr2.length; j++){
if(arr1.indexOf(arr2[j]) === -1){
result.push(arr2[j])
}
}
return result
}
console.log(diffArrayElement([1,2,3,4], [2,3,4,5])) //[1,5]
================================================================================================================================================================================
Code 54: Unique values only from 2 arrays
function diffArrayElement(arr1, arr2){
var combine = arr1.concat(arr2)
return combine.filter( (num)=>{
if(arr1.indexOf(num)== -1 || arr2.indexOf(num)== -1 ) return num
})
}
console.log(diffArrayElement([1,2,3,4], [2,3,4,5])) [1,5]
================================================================================================================================================================================
Code 55: Remove Duplicates from 2 arrays using Set
function uniquefromArrays(arr1, arr2){
let arr = [...arr1, ...arr2]
let unique = [...new Set(arr)];
return unique
}
console.log(uniquefromArrays([1,2,3,4], [2,3,4,5])) //[1,2,3,4,5]
================================================================================================================================================================================
code 56: Sum of all numbers from start to end given number
function sumFromStartToEnd(arr){
var start = Math.min(arr[0], arr[1])
var end = Math.max(arr[0], arr[1])
sum =0
for(var i= start; i<=end; i++){
sum+=i
}
return sum
}
console.log(sumFromStartToEnd([1,4]))
================================================================================================================================================================================
code 57: Remove or Delete elements from an array using various ways
Way 1: Removing Elements from End of a JavaScript Array
var ar = [1, 2, 3, 4, 5, 6];
ar.length = 4; // set length to remove elements
console.log( ar ); // [1, 2, 3, 4]
Way 2: Removing Elements from Beginning of a JavaScript Array
var ar = ['zero', 'one', 'two', 'three'];
ar.shift(); // returns "zero"
console.log( ar ); // ["one", "two", "three"]
Way 3: Using Splice to Remove Array Elements in JavaScript
var list = ["bar", "baz", "foo", "qux"];
list.splice(0, 2); // Starting at index position 0, remove two elements ["bar", "baz"] and retains ["foo", "qux"].
Way 4: Removing Array Items By Value Using Splice
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
for( var i = 0; i < arr.length; i++){
if ( arr[i] === 5) {
arr.splice(i, 1);
}
} // [1, 2, 3, 4, 6, 7, 8, 9, 0]
OR
var arr = [1, 2, 3, 4, 5, 5, 6, 7, 8, 5, 9, 0];
for( var i = 0; i < arr.length; i++){
if ( arr[i] === 5) {
arr.splice(i, 1);
i--;
}
} // [1, 2, 3, 4, 6, 7, 8, 9, 0]
Way 5: Using the Array filter Method to Remove Items By Value
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
var filtered = array.filter(function(value, index, arr){
return value > 5;
}); //filtered => [6, 7, 8, 9]
Way 6: Making a Remove Method
function arrayRemove(arr, value) {
return arr.filter(function(ele){
return ele != value;
});
}
var result = arrayRemove(array, 6); // result = [1, 2, 3, 4, 5, 7, 8, 9, 0]
Way 7: Explicitly Remove Array Elements Using the Delete Operator
var ar = [1, 2, 3, 4, 5, 6];
delete ar[4]; // delete element with index 4
console.log( ar ); // [1, 2, 3, 4, undefined, 6]
================================================================================================================================================================================
Code 58 : Spiral Matrix Printing | Print the elements of a matrix in spiral form
var input = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]];
function run(input, result) {
// add the first row to result
result = result.concat(input.shift());
console.log("res1", result) //[1, 2, 3, 4] //[1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7]
console.log("in1", input) //[[5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] // [[10, 11]]
// add the last element of each remaining row
input.forEach(function(rightEnd) {
result.push(rightEnd.pop());
});
console.log("res2", result) //[1, 2, 3, 4, 8, 12, 16] //[1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11]
console.log("in2", input) //[[5, 6, 7], [9, 10, 11], [13, 14, 15]] // [[10]]
// add the last row in reverse order
result = result.concat(input.pop().reverse());
console.log("res3", result) //[1, 2, 3, 4, 8, 12, 16, 15, 14, 13] //[1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10]
console.log("in3", input) //[[5, 6, 7], [9, 10, 11]]
// add the first element in each remaining row (going upwards)
var tmp = [];
input.forEach(function(leftEnd) {
tmp.push(leftEnd.shift());
});
console.log("res4", result) //[1, 2, 3, 4, 8, 12, 16, 15, 14, 13]
console.log("in4", input) //[[6, 7], [10, 11]]
result = result.concat(tmp.reverse());
console.log("temp", temp) //[9, 5]
console.log("res5", result) //[1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5]
console.log("in5", input) //[[6, 7], [10, 11]]
//again start the function
return run(input, result);
}
console.log('result', run(input, [])); // [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]
================================================================================================================================================================================
Code 59: Currying function i.e sum of multiple argument functions //inner function can access outer function variables but outer functions can't able to acceess inner function.
function sum(a){
return function sum(b){
return function sum(c){
return function sum(d){
return a+b+c+d;
}
}
}
}
console.log(sum(1)(2)(3)(4))
OR
const sum = (a) => (b) => (c) => (d) => a+b+c+d // using ES6
console.log(sum(1)(2)(3)(4))
================================================================================================================================================================================
Code 60: Find SUM, PRODUCT AND AVERAGE of the numbers //accumulation means collection
let arr=[1,2,3,4,5]
let sum = arr.reduce((accum, curr) =>{
return accum + curr;
})
console.log(sum) //15
OR
let sum = arr.reduce((accum, curr) =>{
return accum + curr;
},5) // can set initial value as 5 also
console.log(sum) //20
let product = arr.reduce((accum, curr) =>{
return accum * curr;
})
console.log(product)//120
let average = arr.reduce((accum, curr, index, array) =>{
let total = accum + curr;
if(index === array.length-1){
return total/array.length
}
return total
})
console.log(average)//3
================================================================================================================================================================================
Code 61: Convert 2D/3D array into 1D using reduce function and inbuilt function i.e flat
const arr = [
['a','b'],
['c','d'],
['e','f'],
]
const flatArr = arr.reduce((accum, curr)=>{
return accum.concat(curr)
})
console.log(flatArr) //["a", "b", "c", "d", "e", "f"]
OR
const arr = [
['a','b'],
['c','d'],
['e',['f','g']],
]
console.log(arr.flat(2)) //["a", "b", "c", "d", "e", "f"] //bydefault 1 hota h as a argument
OR
const arr = [
['a','b'],
['c','d'],
['e',['f',['g','h']]],
]
console.log(arr.flat(3)) //["a", "b", "c", "d", "e", "f", "g", "h"]
================================================================================================================================================================================
code 62: Reverse of a nuber using converting into string
function reverseNumber(input){
return(
parseFloat(input.toString().split('').reverse().join(''))*Math.sign(input)
)
}
console.log(reverseNumber(123)) //321
================================================================================================================================================================================
code 63: Reverse of a nuber
function reverseNumber(input){
var result=0;
while(input!=0){ //123 //12 //1
result = result *10; //0*10=0 //3*10=30 // 32*10 =320
result = result + (input%10) //give reminder // 0+3=3 // 30+2=32 //320+1=321
input = Math.floor(input/10) //12 //1
// console.log("in", input)
}
return result
}
console.log(reverseNumber(123)) //321
================================================================================================================================================================================
code 64: Check Armstrong Number
function CheckArmstrongNum(num){ //153
var temp = num;
var result =0;
var a;
while(temp>0){ //153 //15 //1
a= temp%10; //3 //5 //1
temp= parseInt(temp/10) //15 // 1
result= result+a*a*a //0+3*3*3 // 27+ 5*5*5 // 27+ 5*5*5 +1*1*1
}
if(result==num){
return true
}
return false
}
console.log(CheckArmstrongNum(153)) //3*3*3 + 5*5*5 + 1*1*1
================================================================================================================================================================================
code 65: To find the closest number in an array
const needle = 5;
const numbers = [1, 10, 7, 2, 4, 9];
numbers.sort((a, b) => {
return Math.abs(needle - a) - Math.abs(needle - b);
})
console.log(numbers[0]);
================================================================================================================================================================================
code 66: To find the second largest number
function secondLargestNum(arr){
return arr.sort((a, b)=> b - a )[1]
}
console.log(secondLargestNum(['1', '2', '3', '4', '9']))
================================================================================================================================================================================
code 67: To check whether particular word/number present in sentence or not using inbuilt function
function wordInSentence(str){
return str.includes("world"); //true
}
console.log(wordInSentence("Hello world, welcome to the universe."))
OR
var nums =[0,1,3,5,6,7,8,9,7]
console.log(nums.includes(9)) //true
OR
var item=3
console.log(nums.some(x => x === item)) //true
================================================================================================================================================================================
code 68: To check whether particular word/number present in sentence or not using custom function
function checkValueExist(arr, item){
var status = "Not Exist"
for(var i=0; i<arr.length; i++){
if(arr[i]===item){
status = "Exist"
break;
}
}
return status
}
console.log(checkValueExist(['priya', 'riya', 'supriya'], 'priya'))
================================================================================================================================================================================
code 69: To check wheather property exist or not in object
let student ={
name : "priya",
age: 20
}
console.log('name' in student)
OR
console.log(student.hasOwnProperty('name'))
================================================================================================================================================================================
code 70: To dlete the property of an object
let student ={
name : "priya",
age: 20,
city: "pune"
}
delete student.age;
console.log(student)
OR
delete student['name']
console.log(student)
================================================================================================================================================================================
code 71: To find the length of the array in custom way
function findLength(arr){
var len =0;
while(arr[len]!==undefined){
len++
}
return len;
}
console.log(findLength([50,60,70,80,90]))
OR
function findLength(arr){
return arr.length;
}
console.log(findLength([50,60,70,80,90]))
================================================================================================================================================================================
code 72: Star Pattern
for(var i=1; i<=5;i++){ //use to create new row
for(var j=i; j<=5; j++){ //use to add in existing row
document.write("*")
}
document.write("<br/>")
}
*****
****
***
**
*
================================================================================================================================================================================
code 73: Star Pattern
for(var i=1; i<=5;i++){ //use to create new row
for(var j=1; j<=5; j++){ //use to add in existing row
document.write("*")
}