There are few scenarios of Array mentioned below we mostly face while implementing the requirement. Below are the scenarios and the solution given for the same:
Table of Content:
- Remove Item from the Array
- Remove Specific item which occurs number of times in an Array
- Remove Duplicate item from an Array
- Find out number of times same Value Appears in JavaScript Array
Solution: Remove Item from the Array
// Remove only single item 5 from below array
var arr=[1,4,6,5,9];
arr.splice(arr.indexOf(5),1); // syntax arr.indexOf(5) finds out that where is 5
located means at which position in the array. and paramater 1 says that remove
only that single item.
gs.info(arr); // displaying the array after removing.
Solution: Remove Specific item which occurs number of times in an Array
// Remove all the item 5 from the array
var firstArray=[5,5,3,5,8,5,9,5,4,5,9,5];
for(var i=0;i<=firstArray.length;i++){
if(firstArray.indexOf(5)!=-1){
firstArray.splice(firstArray.indexOf(5),1);
}
}
gs.info(firstArray);
Solution: Remove Duplicate item from an Array
var dupValArray=[1,3,5,7,9,5,7,5,10,24,54,5];
var arrayUtil= new ArrayUtil(); // ServiceNow Out of the Box API.
gs.info(arrayUtil.unique(dupValArray));
Solution: Find out number of times same Value Appears in JavaScript Array
// Lets say there is a requirement, that we have to find count of any specific
item in an array.
findReqElementCount(5); // In function we are passing the parameter as 5, which
says that we have to count the item 5 occurrence in an array.
function findReqElementCount(value){
var occArray=[1,3,5,7,9,5,7,5,10,24,54,5];
var count=0;
for(var i=0;i<=occArray.length;i++){
if(occArray[i]==value){
count++;
}
}
gs.info(count);
}
We believe all the information given above related to array scenario's will be helpful. There are lots of other ways to to write code or script for the above scenarios like Removing or deleting Item from the Array, Removing Specific item which occurs number of times in an Array, Remove Duplicate item from an Array, Find out number of times same Value Appears in JavaScript Array etc. If you are come with other scenario's or solution for the above scenario's then please do share with us in below comment section. If you have any question then post the same below, we will try out best to share the solution of the same.
No comments:
Thankyou !!!!