|
| 1 | +//Program to remove duplicates from a list |
| 2 | + |
| 3 | +let list1 = [3,63,24,3,72,3,24] |
| 4 | +console.log( [...new Set(list1)])//[ 3, 63, 24, 72 ] Here we using spread operator(...) and set method to remove duplicate elements |
| 5 | +console.log(new Set(list1))//Set(4) { 3, 63, 24, 72 } |
| 6 | + |
| 7 | +//another way |
| 8 | +const originalArray = [1, 2, 2, 3, 4, 4, 5]; |
| 9 | +const uniqueArray = []; |
| 10 | + |
| 11 | +for (const item of originalArray) { |
| 12 | + if (!uniqueArray.includes(item)) { |
| 13 | + uniqueArray.push(item); |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +console.log(uniqueArray); // Output: [1, 2, 3, 4, 5] |
| 18 | + |
| 19 | +// Write a program to check if a list is empty. |
| 20 | + |
| 21 | +!list1?console.log("list is empty") : console.log("list is not empty") //list is not empty |
| 22 | +if(list1) console.log("list is not empty") |
| 23 | +else console.log("list is empty") // list is not empty |
| 24 | + |
| 25 | +// Write a program to concatenate two lists. |
| 26 | + |
| 27 | +const shiro = [4,26,73,34] |
| 28 | +let newlist = list1.concat(shiro); // concat is a method use to concatenate two arrays |
| 29 | +console.log(newlist); |
| 30 | +//or |
| 31 | +console.log([...list1,...shiro]) |
| 32 | + |
| 33 | +// Write a program to count the number of occurrences of an element in a list. |
| 34 | + |
| 35 | +let elementtocount = 3; // here we giving 3 to know how many 3's occur in the array |
| 36 | +let count = 0; |
| 37 | +for(let i=0;i<list1.length;i++){ |
| 38 | + if(list1[i] === elementtocount){ |
| 39 | + count++ |
| 40 | + } |
| 41 | +} |
| 42 | +console.log(count); |
0 commit comments