Occurance of an element in an Array

In this blog, sharing code to find the occurrence of an element in an Array. In other words, find how many times a elements comes in an array.
Explaination of Shell Script:
1. Here we use dictionary which has key and value pair.
2. keys are mapped to the element of Array here.
3. Setting value of each Key(which is element) equal to 1.
4. Increment the value of key if it comes again by 1.

arr=(4 3 1 1) ## First Array of 4 elements
len_arr=${#arr[@]} ## Length of Array Arr.
i=0
declare -A dict ## Declare Dictionary (key Value Pair)
while [ $i -lt $len_arr ]
do
if [ $i -eq 0 ]
then
dict[${arr[i]}]=1
elif [ -v dict[${arr[i]}] ] ## Checking whether key already exists
then
dict[${arr[i]}]=$((${dict[${arr[i]}]} + 1)) ##Increment value of a key in dictionary dict
else
dict[${arr[i]}]=1
fi
i=$(( $i + 1))
done
##Printing element of an array and its occurrence
for key in “${!dict[@]}”; do
echo “$key ${dict[$key]}”
done

Related posts