Data parser
Bootstrap 5 Data parser plugin
Data Parser is a custom react hook which helps to display your data (.json, .csv) in MDB5 components.
It returns parser
object that has a parse()
method which can transform your data based on selected
options into the required format and set of useful functions for more complicated data
operations.
Note: Read the API tab to find all available options and advanced customization
Datatable
CSV
When parsing CSV into Datatables format (rows and columns), by default all lines are treated
as rows (there is no header included). You can change that by setting
headerIndex
to the position of a header row.
You can customize both columns and rows (values between start/end or only selected indexes).
Note: When you set a headerIndex
, remember to exclude this
value from rows (for example by setting rows.start
to a next index).
Data used in this example: Population Figures
import { useMDBDataParse } from 'mdb-react-data-parser';
import { MDBDatatable } from 'mdb-react-ui-kit';
import React, { useEffect, useState } from 'react';
export default function App() {
const [rows, setRows] = useState<any>([]);
const { parser } = useMDBDataParse('datatable', 'csv', {
rows: { start: 10, end: 14 },
columns: {
indexes: [0, 1, 57, 58],
},
});
useEffect(() => {
fetch('/csv_datatable.csv')
.then((data) => data.text())
.then((data) => {
const { rows } = parser.parse(data);
setRows(rows);
});
}, []);
return (
<MDBDatatable
data={{
columns: ['Country', 'Code', 'Population 2015', 'Population 2016'],
rows,
}}
/>
);
};
JSON
You can define options for rows
in exactly the same way as in CSV format
(start, end / indexes). Instead of doing the same for columns, provide an array of selected
keys to the keys
options.
Data used in this example: Population Figures
import { useMDBDataParse } from 'mdb-react-data-parser';
import { MDBDatatable } from 'mdb-react-ui-kit';
import React, { useEffect, useState } from 'react';
const columns = [
{ label: 'Country', field: 'Country' },
{ label: 'Code', field: 'Country_Code' },
{ label: 'Population 2015', field: 'Year_2015' },
{ label: 'Population 2016', field: 'Year_2016' },
];
export default function App() {
const [rows, setRows] = useState<any>([]);
const { parser } = useMDBDataParse('datatable', 'json', {
rows: { start: 30, end: 100 },
keys: columns.map((columns) => columns.field),
});
useEffect(() => {
fetch('/json_datatable.json')
.then((data) => data.json())
.then((data) => {
const { rows } = parser.parse(data);
setRows(rows);
});
}, []);
return (
<MDBDatatable
data={{
columns,
rows,
}}
/>
);
};
Vector Maps
CSV
Creating a colorMap based on a CSV Data requires identifying the region - Vector Maps uses alpha2Code for IDs, which isn't always convenient. Data Parser can, in most cases, fetch the required identifier based on the country's name or alpha3Code.
Note: If you don't set the step
option to a fixed value, Data
Parser will compute equal size intervals - it may resolve in empty intervals if values are
unevenly distributed.
Data used in this example: Population Figures
import { useMDBDataParse } from 'mdb-react-data-parser';
import { MDBVectorMap } from 'mdb-react-vector-maps';
import React, { useEffect, useState } from 'react';
export default function App() {
const [data, setData] = useState<any>([]);
const { parser } = useMDBDataParse('vectorMap', 'csv', {
color: 'lightGreen',
field: 42,
rows: {
start: 1,
},
step: 8000000,
countryIdentifier: 1,
});
useEffect(() => {
fetch('/csv_vector.csv')
.then((data) => data.text())
.then((data) => {
const { colorMap } = parser.parse(data);
setData(colorMap);
});
}, []);
return <MDBVectorMap readonly fill='white' hover={false} colorMap={data} />;
};
JSON
Apart from a colorMap, parse()
method returns also a legend based on which you
can easily display value-color corelations.
If you're not satisfied with colors available out of the box, you can pass an array of color strings based on which DataParser will create your colorMap.
The getCoordinates()
method helps to find x and y map coordinates based on
longitude and latitude.
Calculated point is an approximation and might not be accurate.
Data used in this example: Population Figures
Population (2016):
import { useMDBDataParse } from 'mdb-react-data-parser';
import { MDBVectorMap } from 'mdb-react-vector-maps';
import React, { useEffect, useState } from 'react';
export default function App() {
const [data, setData] = useState<any>([]);
const { parser } = useMDBDataParse('vectorMap', 'json', {
color: [
'rgba(163, 199, 210, 0.05)',
'rgba(163, 199, 210, 0.1)',
'rgba(163, 199, 210, 0.15)',
'rgba(163, 199, 210, 0.2)',
'rgba(163, 199, 210, 0.25)',
'rgba(163, 199, 210, 0.3)',
'rgba(163, 199, 210, 0.35)',
'rgba(163, 199, 210, 0.4)',
'rgba(163, 199, 210, 0.45)',
'rgba(163, 199, 210, 0.5)',
],
field: 'Year_2016',
step: 8000000,
countryIdentifier: 'Country_Code',
tooltips: (value: any) => `Population: ${value}`,
});
useEffect(() => {
fetch('/json_vector.json')
.then((data) => data.json())
.then((data) => {
const { colorMap } = parser.parse(data);
setData(colorMap);
});
}, []);
return (
<MDBVectorMap
colorMap={data}
fill='rgb(7 43 49)'
tooltips={true}
stroke='#fff'
btnClass='btn-light'
readonly={true}
hover={false}
markers={[
{
...parser.getMapCoordinates(52.107811, 19.94487),
fill: 'rgb(185, 211, 220)',
type: 'bullet',
label: 'Warsaw',
latitude: 52.2297,
longitude: 21.0122,
},
]}
/>
);
};
Charts
CSV
Creating datasets for your Chart component requires two kinds of labels - labels for each
specific dataset (datasetLabel
: column's index) as well as labels for data
points (labelsIndex
: index of a row with labels).
Additionally, you can format the datasetLabel
using
formatLabel
option.
Note: Data Parser generates a color for each dataset, which you can later
use for background/border color. By default, values comes from mdb
palette but
you can also use
full palette
- in this case the color
option's value should refer to the intensity (from 50
to 900).
Basic data
Suitable for most of the chart types (line, bar, horizontal bar, radar, polar, doughnut, pie)
Data used in this example: Population Figures
import { useMDBDataParse } from 'mdb-react-data-parser';
import { MDBChart } from 'mdb-react-ui-kit';
import React, { useEffect, useState } from 'react';
export default function App() {
const [data, setData] = useState<any>({ datasets: [] });
const { parser } = useMDBDataParse('chart', 'csv', {
rows: { start: 170, end: 176 },
datasetLabel: 0,
labelsIndex: 0,
formatLabel: (label: string) => {
return label.replace('Year_', '');
},
});
useEffect(() => {
fetch('/csv_charts_basic.csv')
.then((data) => data.text())
.then((data) => {
const { labels, datasets } = parser.parse(data);
setData({
labels,
datasets: datasets.map((dataset: any) => ({
...dataset,
pointRadius: 0,
borderColor: dataset.color,
color: dataset.color,
})),
});
});
}, []);
return (
<MDBChart
type='line'
data={data}
options={{
plugins: {
tooltip: {
displayColors: false,
},
},
}}
/>
);
};
Coordinates
Parsing data for scatter & bubble charts
import { useMDBDataParse } from 'mdb-react-data-parser';
import { MDBChart } from 'mdb-react-ui-kit';
import React, { useEffect, useState } from 'react';
export default function App() {
const [data, setData] = useState<any>({ datasets: [] });
const { parser: parser8 } = useMDBDataParse('chart', 'csv', {
datasetLabel: 0,
labelsIndex: 0,
rows: {
start: 1,
},
getCoordinates: ([departament, done, team, startDate, currentDate, deadline]: any) => {
const getDayDifference = (firstDate: any, secondDate: any) => {
return (new Date(secondDate).getTime() - new Date(firstDate).getTime()) / (1000 * 3600 * 24);
};
const timeConsumedPercentage = Math.round(
(getDayDifference(startDate, currentDate) / getDayDifference(startDate, deadline)) * 100
);
const targetPercentage = done * 100;
return {
x: timeConsumedPercentage,
y: targetPercentage,
r: team,
};
},
color: 400,
});
useEffect(() => {
fetch('/csv_charts_bubble.csv')
.then((data) => data.text())
.then((data) => {
const { labels, datasets } = parser8.parse(data);
setData({
labels,
datasets: datasets.map((dataset: any) => ({
...dataset,
borderColor: dataset.color,
backgroundColor: dataset.color,
color: dataset.color,
})),
});
});
}, []);
return (
<MDBChart
type='bubble'
data={data}
options={{
plugins: {
tooltip: {
displayColors: false,
},
},
}}
/>
);
};
departament,done,team,startDate,currentDate,deadline
Marketing,0.67,10,2019-03-01,2020-10-23,2020-12-10
Business,0.49,12,2019-01-02,2020-10-23,2020-11-30
Backend,0.88,32,2019-06-01,2020-10-23,2020-11-23
Frontend,0.79,29,2019-08-01,2020-10-23,2020-11-30
Design,0.91,7,2019-07-01,2020-10-23,2020-11-01
JSON
When working with JSON data for you Chart component, you can define which
keys
should be parsed or select all without those specified in the
ignoreKeys
options.
Basic data
Data used in this example: Population Figures
Suitable for most of the chart types (line, bar, horizontal bar, radar, polar, doughnut, pie)
import { useMDBDataParse } from 'mdb-react-data-parser';
import { MDBChart } from 'mdb-react-ui-kit';
import React, { useEffect, useState } from 'react';
export default function App() {
const [data, setData] = useState<any>({ datasets: [] });
const { parser } = useMDBDataParse('chart', 'json', {
datasetLabel: 'Country',
ignoreKeys: ['Country', 'Country_Code'],
rows: { start: 9, end: 14 },
formatLabel: (label: string) => {
return label.replace('Year_', '');
},
color: 100,
});
useEffect(() => {
fetch('/json_charts_basic.json')
.then((data) => data.json())
.then((data) => {
const { labels, datasets } = parser.parse(data);
setData({
labels,
datasets: datasets.map((dataset: any) => ({
...dataset,
pointRadius: 0,
borderColor: dataset.color,
color: dataset.color,
})),
});
});
}, []);
return (
<MDBChart
type='line'
data={data}
options={{
plugins: {
tooltip: {
displayColors: false,
},
},
}}
/>
);
};
Coordinates
Parsing data for scatter & bubble charts
import { useMDBDataParse } from 'mdb-react-data-parser';
import { MDBChart } from 'mdb-react-ui-kit';
import React, { useEffect, useState } from 'react';
export default function App() {
const [data, setData] = useState<any>({ datasets: [] });
const { parser } = useMDBDataParse('chart', 'json', {
datasetLabel: 'departament',
getCoordinates: ({ done, team, startDate, currentDate, deadline }: any) => {
const getDayDifference = (firstDate: any, secondDate: any) => {
return (new Date(secondDate).getTime() - new Date(firstDate).getTime()) / (1000 * 3600 * 24);
};
const timeConsumedPercentage = Math.round(
(getDayDifference(startDate, currentDate) / getDayDifference(startDate, deadline)) * 100
);
const targetPercentage = done * 100;
return {
x: timeConsumedPercentage,
y: targetPercentage,
r: team,
};
},
color: 100,
});
useEffect(() => {
fetch('/json_charts_bubble.json')
.then((data) => data.json())
.then((data) => {
const { labels, datasets } = parser.parse(data);
setData({
labels,
datasets: datasets.map((dataset: any) => ({
...dataset,
borderColor: dataset.color,
backgroundColor: dataset.color,
color: dataset.color,
})),
});
});
}, []);
return (
<MDBChart
type='bubble'
data={data}
options={{
plugins: {
tooltip: {
displayColors: false,
},
},
}}
/>
);
};
[
{
"departament": "Marketing",
"done": 0.67,
"team": 10,
"startDate": "2019-03-01",
"currentDate": "2020-10-23",
"deadline": "2020-12-10"
},
{
"departament": "Business",
"done": 0.49,
"team": 12,
"startDate": "2019-01-02",
"currentDate": "2020-10-23",
"deadline": "2020-11-30"
},
{
"departament": "Backend",
"done": 0.88,
"team": 32,
"startDate": "2019-06-01",
"currentDate": "2020-10-23",
"deadline": "2020-11-23"
},
{
"departament": "Frontend",
"done": 0.79,
"team": 29,
"startDate": "2019-08-01",
"currentDate": "2020-10-23",
"deadline": "2020-11-30"
},
{
"departament": "Design",
"done": 0.91,
"team": 7,
"startDate": "2019-07-01",
"currentDate": "2020-10-23",
"deadline": "2020-11-01"
}
]
Treeview
Using the Treeview requires defining name and children properties in your objects - as it can be an inconvenience, Data Parser allows pointing to other fields as their equivalent (f.e. name -> title, children -> content).
In the same time, you can still make use of other properties (icon, disabled, show) which are not typically defined in data structures. Each of them is a function which takes an object as its argument and returns a field's value depending on your custom logic.
JSON
Note: CSV format is not available for the Treeview component.
import { useMDBDataParse } from 'mdb-react-data-parser';
import { MDBTreeview } from 'mdb-react-treeview';
import { MDBIcon } from 'mdb-react-ui-kit';
import React, { useEffect, useState, useCallback } from 'react';
export default function App() {
const [data, setData] = useState<any>({});
const expandFolder = useCallback(({ name }: { name: string }) => {
const expandedFolders = ['Desktop', 'Programming', 'node_modules'];
return expandedFolders.includes(name);
}, []);
const { parser } = useMDBDataParse('treeview', 'json', {
show: expandFolder,
children: 'content',
name: (el: any) => {
if (el.directory) return el.name;
const getExtensionIcon = (extension: any) => {
const iconMap: any = {
doc: 'file-alt',
js: 'file-code',
zip: 'file-archive',
webp: 'file-image',
pdf: 'file-pdf',
};
return iconMap[extension] || 'file';
};
const icon = getExtensionIcon(el.extension);
return (
<>
<MDBIcon className='mx-2' icon={icon} />
{`${el.name}.${el.extension}`}
</>
);
},
icon: (el: any) => {
const getExtensionIcon = (extension: any) => {
const iconMap: any = {
doc: 'file-alt',
js: 'file-code',
zip: 'file-archive',
webp: 'file-image',
pdf: 'file-pdf',
};
return iconMap[extension] || 'file';
};
const icon = el.directory ? 'folder-closed' : getExtensionIcon(el.extension);
return `<i class="far fa-${icon} mx-2"></i>`;
},
rotationAngle: 0,
});
useEffect(() => {
fetch('/json_treeview.json')
.then((data) => data.json())
.then((data) => {
setData(parser.parse(data));
});
}, []);
return <MDBTreeview className='mb-5' items={data} />;
};
[
{
"name": "Desktop",
"directory": true,
"content": [
{
"name": "Programming",
"directory": true,
"content": [
{
"name": "index",
"extension": "js"
},
{
"name": "README",
"extension": "md"
},
{
"name": "package",
"extension": "json"
},
{
"name": "node_modules",
"directory": true,
"content": [
{
"name": "mdb-ui-kit",
"directory": true
}
]
}
]
},
{
"name": "avatar",
"extension": "webp"
}
]
},
{
"name": "Downloads",
"directory": true,
"content": [
{
"name": "lectures",
"extension": "zip"
},
{
"name": "school-trip",
"extension": "zip"
},
{
"name": "physics-assignment",
"extension": "pdf"
},
{
"name": "presentation",
"extension": "pdf"
},
{
"name": "wallpaper",
"extension": "webp"
}
]
},
{
"name": "Documents",
"directory": true,
"content": [
{
"name": "Homework",
"directory": true,
"content": [
{
"name": "maths",
"extension": "doc"
},
{
"name": "english",
"extension": "doc"
},
{
"name": "biology",
"extension": "doc"
},
{
"name": "computer-science",
"extension": "js"
}
]
}
]
},
{
"name": "Pictures",
"directory": true,
"content": [
{
"name": "Holiday",
"directory": true,
"content": [
{
"name": "1",
"extension": "webp"
},
{
"name": "2",
"extension": "webp"
},
{
"name": "3",
"extension": "webp"
},
{
"name": "4",
"extension": "webp"
}
]
},
{
"name": "School trip",
"directory": true,
"content": [
{
"name": "ABD001",
"extension": "webp"
},
{
"name": "ADB002",
"extension": "webp"
},
{
"name": "ADB004",
"extension": "webp"
},
{
"name": "ADB005",
"extension": "webp"
}
]
}
]
}
]
Data parser - API
Import
import { useMDBDataParse } from 'mdb-react-data-parser';
Usage
const { parser, utils } = useMDBDataParse('datatable', 'csv', options)
parser.parse(data);
utils.flattenDeep(['A', ['B']])
Datatable
CSV options
Name | Type | Default | Description |
---|---|---|---|
rows
|
Object | { start: 0 } |
Defines which rows should be parsed - either with start/end values or an array of indexes. |
rows.start
|
Number | 0 |
Index of the first data row |
rows.end
|
Number |
|
Index of the last data row (when undefined it will be the last available index) |
rows.indexes
|
Array |
|
Set of row's indexes to parse |
columns
|
Object | { start: 0 } |
Defines which columns should be parsed - either with start/end values or an array of indexes. |
columns.start
|
Number | 0 |
Index of the first data column |
columns.end
|
Number |
|
Index of the last data column (when undefined it will be the last available index) |
columns.indexes
|
Array |
|
Set of column indexes to parse |
headerIndex
|
Number | -1 |
Index of the line containing headers (f.e. when set to 0, rows.start should be 1) |
delimiter
|
String | , |
Character separating values in a file |
JSON options
Name | Type | Default | Description |
---|---|---|---|
rows
|
Object | { start: 0 } |
Defines which rows should be parsed - either with start/end values or an array of indexes. |
rows.start
|
Number | 0 |
Index of the first data row |
rows.end
|
Number |
|
Index of the last data row (when undefined it will be the last available index) |
rows.indexes
|
Array |
|
Set of row's indexes to parse |
keys
|
Array |
|
Array of keys (columns) to parse (by default all) |
Methods
Name | Parameters | Description | Example |
---|---|---|---|
parse
|
data (csv/json) | Returns data parsed into the format required by the component (depends on strategy |
parser.parse(csvData)
|
getValueExtrema
|
data (csv/json), field (index/key) | Returns maximum and minimum values in a row |
parser.getValueExtrema(csvData, 3)
|
Vector Maps
CSV options
Name | Type | Default | Description |
---|---|---|---|
rows
|
Object | { start: 0 } |
Defines which rows should be parsed - either with start/end values or an array of indexes. |
rows.start
|
Number | 0 |
Index of the first data row |
rows.end
|
Number |
|
Index of the last data row (when undefined it will be the last available index) |
rows.indexes
|
Array |
|
Set of row's indexes to parse |
headerIndex
|
Number | -1 |
Index of a line containing headers (if set, rows' start should be moved to the next index) |
delimiter
|
String | , |
Character separating values in a file |
color
|
String, Array | 'blue' |
Name of the color palette (see more in section below) or an array of custom colors |
field
|
Number |
|
Index of a value based on which a region should be colored |
countryIdentifier
|
Number |
|
Index of a field containing country identifier (alpha2code, alpha3code, country's name) |
countries
|
Array |
|
Array of identifiers - if defined, only those countries will appear in the colorMap |
tooltips
|
Function |
|
Allows generating custom tooltips |
JSON options
Name | Type | Default | Description |
---|---|---|---|
rows
|
Object | { start: 0 } |
Defines which rows should be parsed - either with start/end values or an array of indexes. |
rows.start
|
Number | 0 |
Index of the first data row |
rows.end
|
Number |
|
Index of the last data row (when undefined it will be the last available index) |
rows.indexes
|
Array |
|
Set of row's indexes to parse |
color
|
String, Array | 'blue' |
Name of the color palette (see more in section below) or an array of custom colors |
field
|
String |
|
Key based on which a region should be colored |
countryIdentifier
|
String |
|
Key containing country identifier (alpha2code, alpha3code, country's name) |
countries
|
Array |
|
Array of identifiers - if set, only those countries will appear in the colorMap |
tooltips
|
Function |
|
Allows generating custom tooltips |
Color maps
Choose one of the colors from our full palette for your color map:
red
pink
purple
deepPurple
indigo
lightBlue
cyan
teal
green
lightGreen
lime
yellow
amber
orange
deepOrange
gray
blueGray
Methods
Name | Parameters | Description | Example |
---|---|---|---|
parse
|
data (csv/json) | Returns data parsed into the format required by the component (depends on strategy |
parser.parse(csvData)
|
getValueExtrema
|
data (csv/json), field (index/key) | Returns maximum and minimum values in a row |
parser.getValueExtrema(csvData, 3)
|
Charts
CSV options
Name | Type | Default | Description |
---|---|---|---|
rows
|
Object | { start: 0 } |
Defines which rows should be parsed - either with start/end values or an array of indexes. |
rows.start
|
Number | 0 |
Index of the first data row |
rows.end
|
Number |
|
Index of the last data row (when undefined it will be the last available index) |
rows.indexes
|
Array |
|
Set of row's indexes to parse |
columns
|
Object | { start: 0 } |
Defines which columns should be parsed - either with start/end values or an array of indexes. |
columns.start
|
Number | 0 |
Index of the first data column |
columns.end
|
Number |
|
Index of the last data column (when undefined it will be the last available index) |
columns.indexes
|
Array |
|
Set of column indexes to parse |
datasetLabel
|
Number |
|
Index of a value in each entry which should be treated as a label for a dataset |
delimiter
|
String | , |
Character separating values in a file |
labelsIndex
|
Number | -1 |
Index of a row in .csv file containing value labels |
formatLabel
|
Function | (label) => label |
Function formatting labels (per value, not dataset) |
color
|
String | mdb |
Color palette from which values will be assigned to datasets |
getCoordinates
|
function |
|
Function which takes an entry as its parameter and should return an object with coordinates (bubble, scatter chart) |
JSON options
Name | Type | Default | Description |
---|---|---|---|
rows
|
Object | { start: 0 } |
Defines which rows should be parsed - either with start/end values or an array of indexes. |
rows.start
|
Number | 0 |
Index of the first data row |
rows.end
|
Number |
|
Index of the last data row (when undefined it will be the last available index) |
rows.indexes
|
Array |
|
Set of row's indexes to parse |
keys
|
Array |
|
Set of keys which should be parsed |
ignoreKeys
|
Array | [] |
Set of keys which should be ignored when parsing |
datasetLabel
|
String |
|
Key which value should be treated as a label for a dataset |
formatLabel
|
Function | (label) => label |
Function formatting labels (per value, not dataset) |
color
|
String | mdb |
Color palette from which values will be assigned to datasets |
getCoordinates
|
function |
|
Function which takes an entry as its parameter and should return an object with coordinates (bubble, scatter chart) |
Colors
Setting the color
attribute to 'mdb'
will assign one of MDB
theme
colors
to each dataset (primary, secondary), while using a number value will iterate through entire
color palette
for given intensity (50, 100, ... 900).
Available values:
mdb
50
100
200
300
400
500
600
700
800
900
Methods
Name | Parameters | Description | Example |
---|---|---|---|
parse
|
data (csv/json) | Returns data parsed into the format required by the component (depends on strategy |
parser.parse(csvData)
|
getValueExtrema
|
data (csv/json), field (index/key) | Returns maximum and minimum values in a row |
parser.getValueExtrema(csvData, 3)
|
Treeview
JSON options
Name | Type | Default | Description |
---|---|---|---|
name
|
String / Function | 'name' |
Reference to the JSON fields that should be a 'name' Treeview structure parameter for items |
children
|
String | 'children' |
Reference to the JSON fields that should be a 'children' Treeview structure parameter for items |
icon
|
String / Function / null | 'null' |
Reference to the JSON fields that should be an 'icon' Treeview structure parameter for items |
show
|
Function / Boolean | 'false' |
Reference to the JSON fields or a static value that should be a 'show' Treeview structure parameter for items |
disabled
|
Function / Boolean | 'false' |
Reference to the JSON fields or a static value that should be a 'disabled' Treeview structure parameter for items |
id
|
String / Number / null | 'null' |
Reference to the JSON fields or a static value that should be an 'id' Treeview structure parameter for items |
rotationAngle
|
Null / Function / Number | 'null' |
Reference to the JSON fields or a static value that should be an 'rotationAngle' Treeview structure parameter for items |
Methods
Name | Parameters | Description | Example |
---|---|---|---|
parse
|
data (json) | Returns data parsed into the format required by the component (depends on strategy |
parser.parse(jsonData)
|
Util functions
Arrays
flattenDeep(array)
Flattens a multi-level array into single-level one.
utils.flattenDeep([1, [2, [3, [4]], 5]]);
// output: [1, 2, 3, 4, 5]
pullAll(array, array)
Pulls particular elements from an array.
utils.pullAll(['a', 'b', 'c', 'a', 'b', 'c'], ['a', 'c']);
// output: ['b', 'b']
take(array, number)
Returns a particular amount of items from the start of an array.
utils.take([1, 2, 3, 4, 5], 2);
// output: [1, 2]
takeRight(array, number)
Returns a particular amount of items from the end of an array.
utils.takeRight([1, 2, 3, 4, 5], 2);
// output: [4, 5]
union(set of arrays)
Concatenates many arrays into one, single-level and removes duplicates.
utils.union([1, 2], [3, ['four', [5]]], ['six']);
// output: [1, 2, 3, 'four', 5, 'six']
unionBy(function / string, set of arrays / objects)
Concatenates many arrays into one, single-level by particular criterium and removes duplicates.
utils.unionBy(Math.floor, [2.1], [1.2, 2.3]);
// output: [2.1, 1.2]
uniq(array)
Returns an array without duplicates.
utils.uniq([1, 2, 1, 3]);
// output: [1, 2, 3]
uniqBy(function / string, array / object)
Returns an array without duplicates set by a particular criterium.
utils.uniqBy(Math.floor, [2.1, 1.2, 2.3]);
// output: [2.1, 1.2]
zip(arrays)
Zips first items of a set of arrays into one array, second ones into second and so on.
utils.zip(['a', 'b'], [1, 2], [true, false]);
// output: [['a', 1, true], ['b', 2, false]]
zipObject(array, array)
Creates an object with keys from the first array and values from the second one.
utils.zipObject(['a', 'b'], [1, 2]);
// output: { 'a': 1, 'b': 2 }
Collections
countBy(array / object, function / string)
Returns an object with values converted using the second parameter as a key and number of items that it matches as a value.
utils.countBy([6.1, 4.2, 6.3], Math.floor);
// output: { 6: 2, 4: 1 }
utils.countBy({ x: 'one', y: 'two', z: 'three', a: 'one' }, 'length');
// output: { 3: 3, 5: 1 }
groupBy(array / object, function / string)
Returns an object with values converted using the second parameter as a key and an array of items that it matches as a value.
utils.groupBy([6.1, 4.2, 6.3], Math.floor);
// output: { 6: [6.1, 6.3], 4: [4.2] }
utils.groupBy({ x: 'one', y: 'two', z: 'three', a: 'one' }, 'length');
// output: { 3: ['one', 'two', 'one'], 5: ['three'] }
sortBy(array / object, array)
Returns a sorted array by values from the second parameter.
const vehicles = [
{ name: 'car', id: 1 },
{ name: 'airplane', id: 4 },
{ name: 'bike', id: 2 },
{ name: 'boat', id: 3 },
];
utils.sortBy(vehicles, ['name', 'id']);
// output:
// [
// { name: 'airplane', id: 4 },
// { name: 'bike', id: 2 },
// { name: 'boat', id: 3 },
// { name: 'car', id: 1 }
// ]
orderBy(array / object, array, array)
Returns a sorted array by values from the second parameter and order from the third one.
const vehicles = [
{ name: 'car', id: 1 },
{ name: 'airplane', id: 4 },
{ name: 'bike', id: 2 },
{ name: 'boat', id: 3 },
];
utils.orderBy(vehicles, ['name', 'id'], ['desc', 'desc']);
// output:
// [
// { name: 'car', id: 1 },
// { name: 'boat', id: 3 },
// { name: 'bike', id: 2 },
// { name: 'airplane', id: 4 }
// ]
Objects
invert(object)
Inverts object keys with their values and overwrites duplicates.
utils.invert({ '1': 'a', '2': 'b', '1': 'c' });
// output: { 'c': '1', 'b': '2' }
invertBy(object, function(optional))
Inverts object keys with their values and puts duplicates into the array.
utils.invertBy({ 'a': '1', 'b': '2', 'c': '1' });
// output: { '1': ['a', 'c'], '2': ['b'] }
utils.invertBy({ 'a': '1', 'b': '2', 'c': '1' }, (key) => `group${key}`);
// output: { 'group1': ['a', 'c'], 'group2': ['b'] }
omit(object, array / string)
Returns object without particular elements.
utils.omit({ 'a': '1', 'b': '2', 'c': '3' }, ['a', 'c']);
// output: { 'b': '2' }
omitBy(object, function)
Returns object without particular elements that are the function result.
utils.omitBy({ 'a': 1, 'b': '2', 'c': 3 }, (item) => typeof item !== 'number');
// output: { 'a': 1, 'c': 3 }
pick(object, array)
Returns particular elements from an object.
utils.pick({ 'a': 1, 'b': '2', 'c': 3 }, ['a', 'c']);
// output: { 'a': 1, 'c': 3 }
pickBy(object, function)
Returns particular elements that are function result from an object.
utils.pickBy({ 'a': 1, 'b': '2', 'c': 3 }, (item) => typeof item !== 'number');
// output: { 'b': '2' }
transform(object, function, accelerator)
Transforms object using a function parameter and accelerator as a start value.
utils.transform(
{ a: 1, b: 2, c: 1 },
function (result, value, key) {
(result[value] || (result[value] = [])).push(key);
},
{}
);
// output: { '1': ['a', 'c'], '2': ['b'] }
More
colorGenerator(array / string / number, number (iterator))
Allows to generate colors from an array.
const colorIterator = utils.colorGenerator(
[
'#FFEBEE',
'#FCE4EC',
'#F3E5F5',
'#EDE7F6',
'#E8EAF6',
'#E3F2FD',
'#E1F5FE',
'#E0F7FA',
'#E0F2F1',
'#E8F5E9',
'#F1F8E9',
'#F9FBE7',
'#FFFDE7',
'#FFF8E1',
'#FFF3E0',
'#FBE9E7',
'#EFEBE9',
'#FAFAFA',
'#ECEFF1',
],
0
);
const color = colorIterator.next().value;
const color2 = colorIterator.next().value;
// 'color' variable is equal to: '#FFEBEE'
// 'color2' variable is equal to: '#FCE4EC'
// You can also use our predefined arrays:
const colorIterator2 = utils.colorGenerator(100, 0);
const color3 = colorIterator2.next().value;
// 'color3' variable is equal to: '#FFCDD2'
const colorIterator3 = utils.colorGenerator('lightGreen', 0);
const color4 = colorIterator3.next().value;
// 'color4' variable is equal to: '#F1F8E9'
getCSVDataArray(data (csv), string (delimiter))
Allows to parse a CSV data to an array.
fetch('data.csv')
.then((data) => data.text())
.then((data) => {
const { utils } = useMDBDataParse()
const parsedData = utils.getCSVDataArray(data, ',');
// 'parsedData' variable is equal to:
// [
// ['departament', 'done', 'team', 'startDate', 'currentDate', 'deadline'],
// ['Marketing', '0.67', '10', '2019-03-01', '2020-10-23', '2020-12-10'],
// ['Business', '0.49', '12', '2019-01-02', '2020-10-23', '2020-11-30'],
// ['Backend', '0.88','32', '2019-06-01', '2020-10-23', '2020-11-23'],
// ['Frontend', '0.79','29', '2019-08-01', '2020-10-23', '2020-11-30'],
// ['Design', '0.91', '7', '2019-07-01', '2020-10-23', '2020-11-01']
// ]
});
departament,done,team,startDate,currentDate,deadline
Marketing,0.67,10,2019-03-01,2020-10-23,2020-12-10
Business,0.49,12,2019-01-02,2020-10-23,2020-11-30
Backend,0.88,32,2019-06-01,2020-10-23,2020-11-23
Frontend,0.79,29,2019-08-01,2020-10-23,2020-11-30
Design,0.91,7,2019-07-01,2020-10-23,2020-11-01