Skip to content

Commit 8341006

Browse files
authored
Merge pull request #7 from Nisarg03/main
Update index.js
2 parents edcdae2 + 55168ad commit 8341006

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

index.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,34 @@
1+
// To throw error in case of invalid datatype.
12
function _throw() {
23
throw new TypeError("Must be a valid array!");
34
}
45

6+
// To check if arr is array.
57
function is_array(arr) {
68
return Array.isArray(arr) ? true : _throw();
79
}
810

11+
// To get the head or first element of the array.
912
function head(arr) {
1013
is_array(arr);
1114
return arr[0];
1215
}
1316

17+
// To get the tail last element of the array.
1418
function 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.
2126
function in_array(arr, value) {
2227
is_array(arr);
2328
return arr.includes(value);
2429
}
2530

31+
// To split arrays into fixed size chunks.
2632
function 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.
4754
function 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.
5563
function 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.
6877
function 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+
7594
export {
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

Comments
 (0)