1+ // To throw error in case of invalid datatype.
12function _throw ( ) {
23 throw new TypeError ( "Must be a valid array!" ) ;
34}
45
6+ // To check if arr is array.
57function is_array ( arr ) {
68 return Array . isArray ( arr ) ? true : _throw ( ) ;
79}
810
11+ // To get the head or first element of the array.
912function head ( arr ) {
1013 is_array ( arr ) ;
1114 return arr [ 0 ] ;
1215}
1316
17+ // To get the tail last element of the array.
1418function tail ( arr ) {
1519 is_array ( arr ) ;
1620 let element = arr . pop ( ) ;
1721 arr . push ( element ) ;
1822 return element ;
1923}
2024
25+ // To check the existence of an element inside the array.
2126function in_array ( arr , value ) {
2227 is_array ( arr ) ;
2328 return arr . includes ( value ) ;
2429}
2530
31+ // To split arrays into fixed size chunks.
2632function array_chunk ( arr , chunk_size ) {
2733 is_array ( arr ) ;
2834 if ( typeof chunk_size != "number" ) {
@@ -44,6 +50,7 @@ function array_chunk(arr, chunk_size) {
4450 }
4551}
4652
53+ // To filter out arrays based on datatypes.
4754function array_filter ( arr ) {
4855 is_array ( arr ) ;
4956 arr = arr . filter ( ( e ) => {
@@ -52,6 +59,7 @@ function array_filter(arr) {
5259 return arr ;
5360}
5461
62+ // To get the frequency of occurence of each unique element inside the array.
5563function array_frequency ( arr ) {
5664 is_array ( arr ) ;
5765 let freq_obj = { } ;
@@ -65,13 +73,24 @@ function array_frequency(arr) {
6573 return freq_obj ;
6674}
6775
76+ // To convert Objects into Arrays.
6877function object_to_array ( obj ) {
6978 let temp = [ ] ;
7079 const entries = Object . entries ( obj ) ;
7180 entries . forEach ( ( ent ) => temp . push ( ent [ 1 ] ) ) ;
7281 return temp ;
7382}
7483
84+ // To get indexes of all occurences of an element inside an array.
85+ function get_all_indexes ( arr , val ) {
86+ is_array ( arr ) ;
87+ var indexes = [ ] ;
88+ for ( let i = 0 ; i < arr . length ; i ++ )
89+ if ( arr [ i ] === val )
90+ indexes . push ( i ) ;
91+ return indexes ;
92+ }
93+
7594export {
7695 head ,
7796 tail ,
@@ -81,4 +100,5 @@ export {
81100 array_filter ,
82101 array_frequency ,
83102 object_to_array ,
103+ get_all_indexes ,
84104} ;
0 commit comments