Can't do this (with a for loop) in node-sqlite3 - node-sqlite3

I need to have the same results with node-sqlite3 because I want to use it in a rest api and it needs to be asynchronous. How can I do this?
When I tried it in node-sqlite3 in a for loop the results where always random. I couldn't understand why. Please help me.
I think it has something to do with the asynchronity from node-sqlite3. But later on I realised I need it to be asynchronous.
In better-sqlite3
const Database = require('better-sqlite3');
const tsePath = './tseFiles/94-ENAR-000.tse';
const db = new Database(tsePath);
let rows = [];
const sqlGetLastId = db.prepare("SELECT COUNT(ROWID) AS countFilledIn FROM WRITE WHERE T2 not null");
const sqlGetLatestRead = db.prepare("SELECT * FROM READ WHERE ROWID = ?");
const sqlGetLanguage = db.prepare("SELECT Dir, Subtag FROM EXTDIR WHERE LangID=?");
const count = sqlGetLastId.get().countFilledIn;
for (let i = 1; i <= count; i++) {
let option = {
id: i,
sourceLang: "",
sourceDir: "",
sourceText: "",
translationLang: "",
translationDir: "",
translationText: ""
};
const result1 = sqlGetLatestRead.get(i);
option.sourceText = result1.source_text;
option.translationText = result1.translated_text1;
const sourceLanguage = result1.source_language;
const translationLanguage = result1.target_language;
const result2 = sqlGetLanguage.get(sourceLanguage);
option.sourceLang = result2.Subtag;
option.sourceDir = result2.Dir;
const result3 = sqlGetLanguage.get(translationLanguage);
option.translationLang = result3.Subtag;
option.translationDir = result3.Dir;
rows.push(option);
}
console.log(rows);
The output is:
[ { id: 1,
sourceLang: 'en',
sourceDir: 'ltr',
sourceText:
'It says—and I’m paraphrasing here—that the key to reading more books is to stop being so precious about it, you idiot.',
translationLang: 'ar',
translationDir: 'rtl',
translationText: 'ن الرائع، هذا النوع من ' },
{ id: 2,
sourceLang: 'en',
sourceDir: 'ltr',
sourceText: '11 softballs',
translationLang: 'ar',
translationDir: 'rtl',
translationText: 'AA' },
{ id: 3,
sourceLang: 'en',
sourceDir: 'ltr',
sourceText:
'Especially if they want to be the "authority" on what\'s hot and what\'s not!',
translationLang: 'ar',
translationDir: 'rtl',
translationText: 'AAA' },
{ id: 4,
sourceLang: 'en',
sourceDir: 'ltr',
sourceText:
'These wallets require more than one user to enter their key before funds can be transferred.',
translationLang: 'ar',
translationDir: 'rtl',
translationText: 'AAAA' },
{ id: 5,
sourceLang: 'en',
sourceDir: 'ltr',
sourceText:
'The Linksys EA8300 Max-Stream router boasts top speeds and tons of features for medium-size homes, and it\'s affordable at $200 or £150 in the UK.',
translationLang: 'ar',
translationDir: 'rtl',
translationText: 'AAAAA' },
{ id: 6,
sourceLang: 'en',
sourceDir: 'ltr',
sourceText: 'Things to See and Do in Hong Kong',
translationLang: 'ar',
translationDir: 'rtl',
translationText: 'AAAAAA' },
{ id: 7,
sourceLang: 'en',
sourceDir: 'ltr',
sourceText:
'Retail isn\'t dying but it is evolving and through that evolution you will see a lot of store closures, but you will see stronger brands emerge.',
translationLang: 'ar',
translationDir: 'rtl',
translationText: 'AAAAAAA' },
{ id: 8,
sourceLang: 'en',
sourceDir: 'ltr',
sourceText:
'Anybody from Iran in the comment section ever hear of these rich kids actually getting in legal trouble or does their families\' wealth protect them? Genuinely just curious.',
translationLang: 'ar',
translationDir: 'rtl',
translationText: 'AAAAAAAA' } ]

Related

Is it possible to iterate through a list of objects and do dynamic tests for each input?

I am currently learning cypress.io, and I have 7 checkboxes representing each day of the week Sun-Sat.
{days.map((day, idx) => (
<input
onChange={(e) => {
const { checked, value } = e.target;
setDays(
days => days.map(data => {
if (data.id === day.id) {
return {
...data,
id: value,
select: !data.select,
};
}
return data;
})
);
setDayId(prev => {
return checked
? [...prev, value] // add if checked
: prev.filter(val => val !== value) // remove if not checked
});
console.log("CHECKING CHECKED VALUE", e.target.checked);
// console.log("WHAT IS THE SET VALUE", values)
}}
key={idx}
name={day?.name}
type="checkbox"
value={day?.id}
checked={day.select}
id="habit-frequency"
/>
))}
And I am trying to avoid doing this 7 times, because I am sure that there is a much better way to do it
cy.get("#habit-frequency")
.should("have.attr", "name", "Sun")
.should("have.attr", "value", "1");
I though about doing this:
const DAYS = [
{ id: 1, name: "Sun", select: false },
{ id: 2, name: "Mon", select: false },
{ id: 3, name: "Tue", select: false },
{ id: 4, name: "Wed", select: false },
{ id: 5, name: "Thu", select: false },
{ id: 6, name: "Fri", select: false },
{ id: 7, name: "Sat", select: false },
];
DAYS.map(day => (
it(`Should have a checkbox for ${day.name}`, () => {
cy.get("#habit-frequency")
.should("have.attr", "name", day.name)
.should("have.attr", "value", day.id)
})
))
But it isn't really working. Any advise? Here is the full test I have written so far in case it helps
describe("Create Habit", () => {
beforeEach(() => {
cy.visit("/");
});
it("Should have a 'Habit' button which can be clicked to display a modal", () => {
cy.get("#modal-btn").should("contain", "Habit").click();
cy.get(".modal-title").should("contain", "Add Habit");
});
it("Should have a 'Add Habit' title, 2 inputs, one for name and one for description, a habit type option, a weekly frequency and an option to choose colors", () => {
cy.get("#modal-btn").click();
cy.get(".modal-title").should("contain", "Add Habit");
cy.get("#habit-name")
.should("have.attr", "placeholder", "Habit name");
cy.get("#habit-description")
.should("have.attr", "placeholder", "Habit description");
cy.get("#habit-todo")
.should("have.attr", "name", "To-Do")
.should("have.attr", "value", "1");
cy.get("#habit-nottodo")
.should("have.attr", "name", "Not-To-Do")
.should("have.attr", "value", "2");
DAYS.map(day => (
it(`Should have a checkbox for ${day.name}`, () => {
cy.get("#habit-frequency")
.should("have.attr", "name", day.name)
.should("have.attr", "value", day.id)
})
))
cy.get("#habit-frequency")
.should("have.attr", "name", "Sun")
.should("have.attr", "value", "1");
});
});
The problem you are having is because you are nesting it calls, Never nest them.
just use your code as is without the internal it call
it(`Should have a checkbox for ${day.name}`, () => { /// this should be removed
..
}/// this should be removed

Yup validation rules issues

Just trying to get a handle on Yup and unfortunately I can't seem to find any examples that point to validating a nested object and a nested array (of objects) within another object.
I have something like this:
"books": [{
"info": {
"dateReleased": null,
"timeReleased": null
},
"reviewers": [
{
"company": "",
"name": ""
}
]
}]
I just have no idea what the required Yup validation syntacx is for info and reviewers as all I want to validate is that the values are not null and are required.
I'vetried this but no validation is firing:
Yup.object().shape({
books: Yup.array(
info: Yup.object({
dateReleased: Yup.date().required('Rquired')
timeReleased: Yup.date().required('Required')
})
reviewers: Yup.array(
Yup.object({
company: Yup.string().required('Required')
name: Yup.string().required('Required')
})
)
)
})
With the above, I'm not getting any console errors but none of my validation rules for info and reviewers are firing.
Yup Validation
const value = {
books: [
{
info: {
dateReleased: null,
timeReleased: null,
},
reviewers: [
{
company: "",
name: "",
},
],
},
],
};
const schema = yup.object().shape({
books: yup.array(
yup.object().shape({
info: yup.object().shape({
dateReleased: yup.date().required('Required'),
timeReleased: yup.date().required('Required')
}),
reviewer: yup.array(
yup.object().shape({
company: yup.string().required('Required'),
name: yup.string().required('Required')
})
)
})
),
});
schema.validate(value).catch(err => {
console.log(err.name); // ValidationError
console.log(err.errors); // [books[0].info.timeReleased must be a `date` type, but the final value was: `Invalid Date`.]
});

How to loop through JSON Object in vue js

I am working on vue.js and backend is laravel. I am new to these technologies.
I am trying to display data in parent and child rows in a table base on vue material syntax.
My Laravel controlller function contains the code
$tasks = Task::select('tasks_status', DB::raw("group_concat(CONCAT('{\"id\":\"',id,'\",\"name\":\"',name,'\"}') ) as subrow"))
->where('tasks_status', '<>', "Sent Tasks")
->whereNull('user_id')
->orderBy('id', 'desc')
->groupBy('tasks_status')
->get();
I am trying to get data grouped by task_status. For each task status there are multiple rows.
My JSON is like below -
[
{
"tasks_status": "Completed Task",
"subrow": "{\"id\":\"4\",\"name\":\"d1\"}"
},
{
"tasks_status": "My Tasks",
"subrow": "{\"id\":\"2\",\"name\":\"b1\"},{\"id\":\"7\",\"name\":\"g1\"}"
}
]
Online JSON Parser validates it.
in Vue Front end I try to display this JSON data using 2 for loops Like below
<md-table v-model="searched" md-sort="name" md-sort-order="asc" md-fixed-header class="table-sort">
<md-table-toolbar>
<div class="md-toolbar-section-start">
<h1 class="md-title">Tasks</h1>
</div>
<md-field md-clearable class="md-toolbar-section-end">
<label for="Tasks">Tasks</label>
<md-select v-model="fieldsSearchTerm.searchTermForDataTable" name="search" id="search" #input="searchOnTable" >
<md-option value="">All Tasks</md-option>
<md-option value="My Tasks">My Tasks</md-option>
<md-option value="Organization Tasks"
>Organization Tasks</md-option
>
<md-option value="Received Tasks"
>Received Tasks</md-option
>
<md-option value="Completed Task"
>Completed Task</md-option
>
<md-option value="Incomplete Tasks"
>Incomplete Tasks</md-option
>
<md-option value="Sent Tasks">Sent Tasks</md-option>
</md-select>
</md-field>
<md-field md-clearable class="md-toolbar-section-end">
<b-button class="btn btn-danger modal-btn" block #click="changeStatusToDone">Done</b-button>
</md-field>
</md-table-toolbar>
<md-table-empty-state
md-label="No data found">
</md-table-empty-state>
<md-table-row slot="md-table-row" v-for="rowHeading in searched" >
<md-table-cell md-label="Task Name" md-sort-by="name">{{ rowHeading.tasks_status }}</md-table-cell>
<md-table-cell md-label="Task Status" md-sort-by="tasks_status"></md-table-cell>
<md-table-cell md-label="Due Date" md-sort-by="due_date"></md-table-cell>
<md-table-cell md-label="Priority" md-sort-by="priority"></md-table-cell>
<md-table-cell md-label="Actions" md-sort-by="">
</md-table-cell>
</md-table-row>
<md-table-row slot="md-table-row" v-for="subRowElements in rowHeading.subrow">
<md-table-cell md-label="" md-sort-by="" >
</md-table-cell>
<md-table-cell colspan=4 md-label="Task Name" md-sort-by="name">hi {{ subRowElements }}</md-table-cell>
</md-table-cell>
</md-table-row>
</md-table>
In My JS I have code like this below
import Cookies from 'js-cookie'
import axios from "axios"
import Vue from 'vue'
import VueResource from 'vue-resource'
import Form from 'vform'
const toLower = text => {
return text.toString().toLowerCase()
}
const searchByName = (items, term) => {
if (term) {
return items.filter(item => toLower(item.tasks_status).includes(toLower(term)))
}
return items
}
export default {
name: 'TableSearch',
components: {
},
data() {
form: new Form({
tasks_statusUpdate: '',
nameUpdate: '',
priorityUpdate: '',
task_descriptionUpdate: '',
dueDateUpdate: '',
taskAssignedToUserUpdate: '',
_token: Cookies.get('token')
})
return {
goods: [],
fieldsUpdate: {
tasks_statusUpdate: "",
nameUpdate: "",
priorityUpdate: "",
task_descriptionUpdate: '',
dueDateUpdate: "",
taskAssignedToUserUpdate: "",
_token: Cookies.get('token'),
},
fieldsView: {
tasks_statusView: "",
nameView: "",
priorityView: "",
task_descriptionView: '',
dueDateView: "",
taskAssignedToUserView: "",
userNameView: "",
},
fieldsTaskDone: {
tasks_status: 1,
},
fieldsSearchTerm: {
searchTermForDataTable: '',
},
fieldsCheckBox: {
cboTaskName: true,
cboTaskStatus: true,
cboDueDate: true,
cboPriority: true,
},
isOpen: true,
rows: null,
allUsersUpdate: [],
searched: [],
rowHeading:[],
subRowElements:[],
users: [
{
id: 1,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 2,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 3,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 4,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 5,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 6,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 7,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 8,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 9,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 10,
name: "Shawna vishal",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
],
rows: [],
editing_record_id: 0,
view_record_id: 0,
checkedTaskIDs: [],
dynamicColumn: [],
}
},
methods: {
newUser () {
window.alert('Noop')
},
searchOnTable () {
this.makeGetRequest();
this.searched = searchByName(this.rows, this.search)
},
fnDynamicColumns: function(e){
if (e.target.checked) {
console.log(e.target.value)
}
},
check_task_id: function(e) {
if (e.target.checked) {
console.log(e.target.value)
}
},
changeStatusToDone () {
axios
.post("api/v1/tasks/"+this.checkedTaskIDs+"/complete",
this.fieldsTaskDone
)
.then(response => {
alert("Task Done!");
})
.catch(error => {
console.log(error);
});
this.makeGetRequest();
},
async makeGetRequest() {
console.log("makeGetRequest begin ");
var fnRows = [];
await axios.get('api/v1/tasks', {
params: {
searchTermForDataTable: this.fieldsSearchTerm.searchTermForDataTable
}
})
.then((response) => {
this.rows = response.data;
fnRows = response.data;
console.log("inside axios > makeGetRequest" + JSON.stringify(this.rows));
});
this.searched = this.rows
console.log("makeGetRequest later " + this.searched);
},
async getAllUsers() {
console.log("table > getAllUsers begin ");
await axios.get('api/v1/getallusers')
.then((response) => {
this.allUsersUpdate = response.data;
});
console.log("table > outside axios user11" + this.allUsersUpdate);
},
submitUpdateForm() {
console.log(this.fieldsUpdate);
console.log(Cookies.get('token'));
axios
.put("api/v1/tasks/"+this.editing_record_id,
this.fieldsUpdate
)
.then(response => {
alert("Task Updated!");
//this.fields = {};
})
.catch(error => {
console.log(error);
});
this.makeGetRequest();
console.log("ppppnnnnnn");
},
async getTask() {
await axios.get('api/v1/tasks/'+this.editing_record_id)
.then((response) => {
this.fieldsUpdate.tasks_statusUpdate = response.data[0].tasks_status;
this.fieldsUpdate.nameUpdate = response.data[0].name;
this.fieldsUpdate.taskAssignedToUserUpdate = response.data[0].user_id;
this.fieldsUpdate.priorityUpdate = response.data[0].priority;
this.fieldsUpdate.task_descriptionUpdate = response.data[0].task_description;
if(response.data[0].due_date !== null)
{
this.fieldsUpdate.dueDateUpdate = response.data[0].due_date;
}
console.log("getTask With Join" + JSON.stringify(response.data[0]));
});
console.log("getTask With Join" + JSON.stringify(this.fieldsUpdate));
},
showUpdateModal(id) {
this.editing_record_id = id;
this.getTask();
this.$bvModal.show('taskUpdateModal')
},
softDeleteTask(id) {
if(confirm("Are you sure, you want to delete, this task?")){
axios
.delete("api/v1/tasks/"+id)
.then(response => {
alert("Task Deleted!");
//this.fields = {};
})
.catch(error => {
console.log(error);
});
this.makeGetRequest();
}
},
async getTaskForView() {
await axios.get('api/v1/tasks/'+this.view_record_id)
.then((response) => {
this.fieldsView.tasks_statusView = response.data[0].tasks_status;
this.fieldsView.nameView = response.data[0].name;
this.fieldsView.taskAssignedToUserView = response.data[0].user_id;
this.fieldsView.priorityView = response.data[0].priority;
this.fieldsView.task_descriptionView = response.data[0].task_description;
this.fieldsView.dueDateView = response.data[0].due_date;
this.fieldsView.userNameView = response.data[0].userName;
});
console.log("getTask" + JSON.stringify(this.fieldsView));
},
showViewModal(id) {
this.view_record_id = id;
this.getTaskForView();
this.$bvModal.show('taskViewModal')
},
},
created () {
console.log("inside created()1");
this.makeGetRequest();
this.getAllUsers();
console.log("outside axios" + this.rows);
enter code here
console.log("inside created() 2");
},
mounted() {
console.log("inside mounted()")
},
}
Can Anybody suggests a way to get valid JSON from controller and display it with correct loops in vue.js page. Thanks in advance.
I think you should use something like this in your Laravel controller, and then it would be easier to use loop to output json
$tasks = Task::select('tasks_status', DB::raw("group_concat(CONCAT('{\"id\":\"',id,'\",\"name\":\"',name,'\"}') ) as subrow"))
->where('tasks_status', '<>', "Sent Tasks")
->whereNull('user_id')
->orderBy('id', 'desc')
->groupBy('tasks_status')
->get()->map(function ($e) {
$e->subrow = json_decode($e->subrow);
return $e;
});

Yup: deep validation in array of objects

I have a data structure like this:
{
"subject": "Ah yeah",
"description": "Jeg siger...",
"daysOfWeek": [
{
"dayOfWeek": "MONDAY",
"checked": false
},
{
"dayOfWeek": "TUESDAY",
"checked": false
},
{
"dayOfWeek": "WEDNESDAY",
"checked": true
},
{
"dayOfWeek": "THURSDAY",
"checked": false
},
{
"dayOfWeek": "FRIDAY",
"checked": false
},
{
"dayOfWeek": "SATURDAY",
"checked": true
},
{
"dayOfWeek": "SUNDAY",
"checked": true
}
],
"uuid": "da8f56a2-625f-400d-800d-c975bead0cff",
"taskSchedules": [],
"isInitial": false,
"hasChanged": false
}
In daysOfWeek I want to ensure that at least one of the items has checked: true.
This is my validation schema so far (but not working):
const taskValidationSchema = Yup.object().shape({
subject: Yup.string().required('Required'),
description: Yup.string(),
daysOfWeek: Yup.array()
.of(
Yup.object().shape({
dayOfWeek: Yup.string(),
checked: Yup.boolean(),
})
)
.required('Required'),
taskSchedules: Yup.array(),
})
Is it possible to validate the values of daysOfWeek ensuring that at least one of them has checked: true?
I solved it using compact() (filtering out falsely values) together with setTimeout after the FieldArray modifier function:
const validationSchema = Yup.object().shape({
subject: Yup.string().required(i18n.t('required-field')),
description: Yup.string(),
daysOfWeek: Yup.array()
.of(
Yup.object().shape({
dayOfWeek: Yup.string(),
checked: Yup.boolean(),
})
)
.compact((v) => !v.checked)
.required(i18n.t('required-field')),
taskSchedules: Yup.array(),
});
And in form:
<Checkbox
value={day.dayOfWeek}
checked={day.checked}
onChange={(e) => {
replace(idx, { ...day, checked: !day.checked });
setTimeout(() => {
validateForm();
});
}}
/>;
Base on #olefrank's answer. This code work with me.
const validationSchema = Yup.object().shape({
subject: Yup.string().required(i18n.t('required-field')),
description: Yup.string(),
daysOfWeek: Yup.array()
.of(
Yup.object().shape({
dayOfWeek: Yup.string(),
checked: Yup.boolean(),
})
)
.compact((v) => !v.checked)
.min(1, i18n.t('required-field')), // <– `.min(1)` instead of `.required()`
taskSchedules: Yup.array(),
});
I have done this type of validation in my Node.js(Express.js) project. You can try validation in this way.
const validationSchema = yup.object({
subject: yup.string().required(),
description: yup.string().required(),
daysOfWeek: yup.array(
yup.object({
dayOfWeek: yup.string().required(),
checked: yup.boolean().required()
})
)
})
If you trying in latest version it should be used like this
Yup.array().min(1, "At least one option is required").required()
In my case I have used formik with yup for this,
I want to select only one value in an array if not selected I need to display the error
array = [{"label": "Option 1", "selected": false, "value": "option-1"}, {"label": "Option 2", "selected": false, "value": "option-2"}, {"label": "Option 3", "selected": false, "value": "option-3"}]
Yup.mixed().test({
message: 'Required',test:
val => val.filter(i => i.selected === true).length === 1})
it worked for me
Yup.mixed().test({
message: 'Required',test:
val => val.filter(i => i.selected === true).length !== 0})

Sort a list of maps in Dart - Second Level Sort in Dart

I have a list of maps like this:
var associations = [{'name': 'EG', 'description': 'Evil Genius'},
{'name': 'NaVi', 'description': 'Natus Vincere'}];
var members = [
{'associationName': 'EG', 'firstName': 'Bob', 'lastName': 'Dylan', 'email': 'bd#gmail.com'},
{'associationName': 'NaVi', 'firstName': 'John', 'lastName': 'Malkovich', 'email': 'jm#gmail.com'},
{'associationName': 'EG', 'firstName': 'Charles', 'lastName': 'Darwin', 'email': 'cd#gmail.com'}
];
I would like to write a code that would sort the list of members alphabetically by the last name first, then by the first name. Moreover, I would like to be able to find members whose lastnames start with a specifiedd letter. By example, with D, we would get Bob Dylan and Charles Darwin. I am able to manage it with a single map or a single list, but combining a list of maps makes it more difficult.
Thanks for your help.
To sort :
members.sort((m1, m2) {
var r = m1["lastName"].compareTo(m2["lastName"]);
if (r != 0) return r;
return m1["firstName"].compareTo(m2["firstName"]);
});
To filter :
members.where((m) => m['lastName'].startsWith('D'));
List<Map> myList = [
{ 'name' : 'ifredom','age':23},
{ 'name' : 'JackMa','age':61},
{ 'name' : 'zhazhahui','age':48},
];
myList.sort((a, b) => (b['age']).compareTo(a['age'])); /// sort List<Map<String,dynamic>>
print(myList);
final data = [
EmployerModel(id: "1", image: "", name: "A"),
EmployerModel(id: "1", image: "", name: "A"),
EmployerModel(id: "1", image: "", name: "B"),
EmployerModel(id: "1", image: "", name: "B"),
EmployerModel(id: "1", image: "", name: "C"),
EmployerModel(id: "1", image: "", name: "E"),
EmployerModel(id: "1", image: "", name: "E"),
EmployerModel(id: "1", image: "", name: "E"),
EmployerModel(id: "1", image: "", name: "G"),
];
var firstAlph = data[0].name![0];
List<Map<String, dynamic>> d = [];
data.forEach((element) {
if (element.name![0] == firstAlph) {
if (d.isEmpty) {
d.add({
firstAlph: [element],
});
} else {
d.forEach((e) {
if (e.keys.contains(firstAlph)) {
e[firstAlph].add(element);
}
});
}
} else {
firstAlph = element.name![0];
d.add({
firstAlph: [element],
});
}
});
debugPrint(d.toString());
This will give a List in alphabetical order which will make you're UI look much better.
Output example:
["A":[data,data,data],"B":[data,data,data]]

Resources