Guilherme Ranoya, 2021
Small functions to help dealing with data in javascript. Tools for manipulating data in arrays and objects.
Load the library from the web if you wish:
<script src="datat.vercel.app/basics.js"></script>
The reference and examples are commented in the source code.
Get a json from a URL
xpto = getdata(myurl, callback);
callback = function (data) {
// data is the JSON data fetched
};
xpto = dayadd(originaldate, days);
Example:
mystringdate = "11/04/2022";
newdate = dayadd(mystringdate, 7);
day = howmanydaysincluding(firstdate, seconddate);
Example:
dayspassed = howmanydaysincluding("11/04/2022", "15/04/2022");
Create a list array from an old one when their elements have any value on a specific criteria(key)
xpto = bfilter(array, criteria);
Example:
separate = bfilter(oldarray, "active");
List of unique values from a criteria (key) in the array
newarray = unique(oldarray, criteria);
Sort an array using a list of possible values for a specific key
newarray = sortbylist(oldarray, keyvaluesarray, key);
Example:
disordered = [
{ fruit: "orange", quantity: 5, type: "B" },
{ fruit: "apple", quantity: 2, type: "A" },
{ fruit: "banana", quantity: 3, type: "B" },
{ fruit: "apple", quantity: 10, type: "B" },
{ fruit: "strawberry", quantity: 5, type: "A" },
];
list = ["strawberry", "apple"];
orders = sortbylist(disordered, list, "fruit"); // Array(3):
// [
// {'fruit': 'strawberry', 'quantity': 5, 'type': 'A'},
// {'fruit': 'apple', 'quantity': 2, 'type': 'A'},
// {'fruit': 'apple', 'quantity': 10, 'type':'B'}
// ]
Extract all Tags (words marking some criteria) in an array of objects, in a specific key of the object
newarray = tags(array, key, separator);
Example:
alltags = tags(myarray, "categories", ",");
Create a filtered array using a function to filter data
newarray = select(
oldarray,
function (n, arr, patt) {
// if(patt.test(arr.valr)) {
// n.push(arr);
// }
},
patt
);
Using Select Predefined Tools:
newarray = select(oldarray,patterncheck,/mypattern/gi);
Functions to pair with Select Function
Uses regex for check
Implementation of Observable's Inputs.search
You will need:
- a
<input>
element in your HTML; - to create an omnifilter(arr) function, which will update everything in your document with data filtered by what is in the
<input>
element; - a JSON file in an URL.
Example:
omnifilter = function (arr) {
console.table(arr);
};
omnifilterfetchdata("https://www.myurl/file.json", "inputelementID");
arr is the array created/updated from the JSON file being filtered by <input>