Array operation in Javascript

1)Problem : You have given an array in unsorted way. Find the occurance of each element in array

Hint : Use object key concept

Solution 1 :

// Reduce time complexity
var arr = [1, 2, 3, 4, 5, 1, 3, 6, 7];
let counts = {};
arr.forEach(el => {
counts[el] = (counts[el] || 0) + 1;
});
console.log('duplicate counts--->', counts);

Solution 2 :

var arr = [1,11,1,22,1,3,3,1,3];
var obj = {};
arr.forEach((ele)=>{
document.write("-->",obj[ele])
if(obj[ele] != undefined){
obj[ele] = obj[ele] + 1;
}
else{
obj[ele] = 1;
}
});
document.write("The fast object is ",JSON.stringify(obj));

2)Problem : You have given an array. Reverse it

Solution 1 :

<script>
var arr = [2,77,1,6,7];
var tmpArr = [];
for(i=0;i<arr.length;i++){
tmpArr.push(arr[arr.length-(i+1)])
}
document.write('The reversed array is ',tmpArr);
</script>

By Pankaj Kumar Agarwal

1 comments On Array operation in Javascript

  • Essential Vanilla JavaScript Functions. Some of the missing functions in JavaScript in vanilla form (inspired by PHP). You can just try it as a programming practice. Array Functions. Array _unique(). Remove duplicates from an array .

Leave a reply:

Your email address will not be published.