Typescript - Rearrange specific object - javascript

I've arranged object in alphabetical order. I wanna move "Others" at last in dropdown. Is there any way to acheive this?
this.registrationMerchantService.getBusinessCategories().subscribe(response => {
this.businessCategories = response;
this.businessCategories.sort(function(a, b) {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
});
});
Json objects
export const BUSINESS_CATEGORIES: BusinessCategory[] = [
{ id: 1, name: 'Food & Beverage' },
{ id: 2, name: 'Transportation & Travel' },
{ id: 3, name: 'Fashion' },
{ id: 4, name: 'Leisure' },
{ id: 5, name: 'Digital Content' },
{ id: 6, name: 'Health and Beauty' },
{ id: 7, name: 'Online Shopping' },
{ id: 8, name: 'Telecommunications' },
{ id: 9, name: 'Utilities' },
{ id: 10, name: 'Others' },
{ id: 11, name: 'General' },
{ id: 12, name: 'Insurance' },
{ id: 13, name: 'Services' },
{ id: 14, name: 'Appliances' },
{ id: 15, name: 'Entertainment' },
{ id: 16, name: 'Household Goods & Groceries' },
];
Current result:
Is there any idea to move "Others" at last in the dropdown list

You can try sorting the array filtering out "Others" and then add it at the end:
var categories = [
{ id: 1, name: 'Food & Beverage' },
{ id: 2, name: 'Transportation & Travel' },
{ id: 3, name: 'Fashion' },
{ id: 4, name: 'Leisure' },
{ id: 5, name: 'Digital Content' },
{ id: 6, name: 'Health and Beauty' },
{ id: 7, name: 'Online Shopping' },
{ id: 8, name: 'Telecommunications' },
{ id: 9, name: 'Utilities' },
{ id: 10, name: 'Others' },
{ id: 11, name: 'General' },
{ id: 12, name: 'Insurance' },
{ id: 13, name: 'Services' },
{ id: 14, name: 'Appliances' },
{ id: 15, name: 'Entertainment' },
{ id: 16, name: 'Household Goods & Groceries' },
];
const sorted = categories.sort(function(a, b) {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
});
console.log(
sorted
.filter(x=>x.name!=="Others")//remove "Others"
.concat(sorted.find(x=>x.name==="Others"))//add "Others" at the end
);

You can create a function that accepts an ignore list, and you can return a sorting function that takes care of ignoring certain names, by placing them above or below in the list.
You can fiddle with the sorting direction to get the desired result.
var BUSINESS_CATEGORIES = [
{ id: 1, name: 'Food & Beverage' },
{ id: 2, name: 'Transportation & Travel' },
{ id: 3, name: 'Fashion' },
{ id: 4, name: 'Leisure' },
{ id: 5, name: 'Digital Content' },
{ id: 6, name: 'Health and Beauty' },
{ id: 7, name: 'Online Shopping' },
{ id: 8, name: 'Telecommunications' },
{ id: 9, name: 'Utilities' },
{ id: 10, name: 'Others' },
{ id: 11, name: 'General' },
{ id: 12, name: 'Insurance' },
{ id: 13, name: 'Services' },
{ id: 14, name: 'Appliances' },
{ id: 15, name: 'Entertainment' },
{ id: 16, name: 'Household Goods & Groceries' },
];
let categories = this.BUSINESS_CATEGORIES.sort(customSort([ 'Others' ], 1));
console.log(JSON.stringify(categories, null, 2));
function customSort(ignoreList, direction) {
ignoreList = ignoreList || [];
direction = direction || 1;
return function(a, b) {
var aPos = ignoreList.indexOf(a.name);
var bPos = ignoreList.indexOf(b.name);
if (bPos > -1) return -1 * direction;
if (aPos > -1) return 1 * direction;
return a.name.localeCompare(b.name) * direction;
}
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

Related

How to reduce an array and add a count as a new field?

I have an array of objects, however i need the array to add a count onto each object, and also remove any duplicates. Is there a simple way to achieve this?
CURRENT
[
{ id: 2, name: 'Adventure' },
{ id: 6, name: 'Crime' },
{ id: 2, name: 'Adventure' },
{ id: 3, name: 'Beautiful' },
{ id: 7, name: 'Drama' },
{ id: 2, name: 'Adventure' }
]
EXPECTED
[
{ id: 2, name: 'Adventure', count: 3 },
{ id: 6, name: 'Crime', count: 1 },
{ id: 3, name: 'Beautiful', count: 1 },
{ id: 7, name: 'Drama', count: 1 }
]
let current = [
{ id: 2, name: 'Adventure' },
{ id: 6, name: 'Crime' },
{ id: 2, name: 'Adventure' },
{ id: 3, name: 'Beautiful' },
{ id: 7, name: 'Drama' },
{ id: 2, name: 'Adventure' }
]
let expected = current.reduce((acc, cur) => {
let curFind = acc.find(item => item.id === cur.id)
if (curFind) {
curFind.count++
return acc
} else {
return [...acc, {
...cur,
count: 1
}]
}
}, [])
console.log('expected:', expected)

search an item in multidimentionnal array

I'm trying to find an element on a multidimentionnal array usin JAVASCRIPT function, but I get error
This is my array's data:
export const datas = [
{
id: 1,
firstName: 'John',
tables: [
{ ID: 11, title: 'Lorem' },
{ ID: 12, title: 'Ipsum' },
],
},
{
id: 2,
firstName: 'Doe',
tables: [
{
ID: 22,
title: 'Arke',
nodes: [{ name: 'Name1' }, { name: 'Name2' }, { name: 'Name3' }],
},
{ ID: 23, title: 'Korem' },
],
},
{
id: 3,
firstName: 'Brad',
tables: [
{
ID: 30,
title: 'Mern',
nodes: [{ name: 'Name4' }, { name: 'Name5' }, { name: 'Name6' }],
},
{
ID: 31,
title: 'Full',
nodes: [{ name: 'Name7' }, { name: 'Name8' }, { name: 'Name9' }],
},
],
},
];
I've tried a reccursive function but it's not work, this is my code :
export const findById = (arr, id) => {
for (let o of arr) {
if (o.tables.length > 0) {
let a = findById(o.tables.nodes, 'id');
console.log(a);
}
}
};
I want to print the Object with ID 22, the problem is that I don't have the same structure in each dimension, and it still confuse me..
My Input : 22
My output :
{
ID: 22,
title: 'Arke',
nodes: [{ name: 'Name1' }, { name: 'Name2' }, { name: 'Name3' }],
},
Have you an idea how to edit my function to get my input's response ?
Your recursive function wasn't too far off, you need to check if the item as a tables first before recursively calling it again. And then finally just check the ID in the loop.
eg..
const datas=[{id:1,firstName:"John",tables:[{ID:11,title:"Lorem"},{ID:12,title:"Ipsum"}]},{id:2,firstName:"Doe",tables:[{ID:22,title:"Arke",nodes:[{name:"Name1"},{name:"Name2"},{name:"Name3"}]},{ID:23,title:"Korem"}]},{id:3,firstName:"Brad",tables:[{ID:30,title:"Mern",nodes:[{name:"Name4"},{name:"Name5"},{name:"Name6"}]},{ID:31,title:"Full",nodes:[{name:"Name7"},{name:"Name8"},{name:"Name9"}]}]}];
function findById(arr, ID) {
for (const a of arr) {
if (a.tables) {
const r = findById(a.tables, ID);
if (r) return r;
}
if (a.ID === ID) return a;
}
}
console.log(findById(datas, 22));
if you just need the nested data you can use flatMap and find
const findById = (arr, id) =>
arr
.flatMap(d => d.tables)
.find(t => t.ID === id)
const datas = [{
id: 1,
firstName: 'John',
tables: [{
ID: 11,
title: 'Lorem'
},
{
ID: 12,
title: 'Ipsum'
},
],
},
{
id: 2,
firstName: 'Doe',
tables: [{
ID: 22,
title: 'Arke',
nodes: [{
name: 'Name1'
}, {
name: 'Name2'
}, {
name: 'Name3'
}],
},
{
ID: 23,
title: 'Korem'
},
],
},
{
id: 3,
firstName: 'Brad',
tables: [{
ID: 30,
title: 'Mern',
nodes: [{
name: 'Name4'
}, {
name: 'Name5'
}, {
name: 'Name6'
}],
},
{
ID: 31,
title: 'Full',
nodes: [{
name: 'Name7'
}, {
name: 'Name8'
}, {
name: 'Name9'
}],
},
],
},
];
console.log(findById(datas, 22))
js has amazing array options https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
the ones which will help you most are probably:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap
here are some examples
// get the base with id 22
const baseWith22ID = datas.filter(f => f.tables.filter(s => s.id = 22))
// (i guess you want this one) get all elements with id 22
const onlyElementsWith22ID = datas.flatMap(f => f.tables.filter(s => s.id = 22))

find method not returning '0th' matched object react, or react-native or javascript

Not getting all matched objects, its is returning all objects except '{ ID:0, Name: 'General Group' }', i want all matched objects
let arrDashboardIconGroups = [
{ ID:0, Name: 'General Group' },
{ ID: 1, Name: 'Patient Administration' },
{ ID: 2, Name: 'Medical Charts' },
{ ID: 3, Name: 'Medical Procedures' },
{ ID: 13, Name: 'Purchase' },
{ ID: 14, Name: 'Sales' },
{ ID: 5, Name: 'Insurance' },
{ ID: 4, Name: 'Cash' },
{ ID: 6, Name: 'Pharmacy' },
{ ID: 7, Name: 'Inventory' },
{ ID: 8, Name: 'Lab' },
{ ID: 9, Name: 'Imaging' },
{ ID: 10, Name: 'In Patient' },
{ ID: 11, Name: 'System Administration' },
{ ID: 12, Name: 'Accounting' }
]
const getMatchedobjects=()=> {
let result = [0,1,2,3,4,]
let matchedArray = arrDashboardIconGroups.filter(val =>result.find(
(items)=>items == val.ID))
console.log(matchedArray)
}
getMatchedobjects()
You are returning the value of
result.find((items) => items == val.ID)
In the first case, the value returned is 0 which is a falsy value. So It won't include in the final filter result.
You can run the below code and see the returning values.
let arrDashboardIconGroups = [
{ ID: 0, Name: "General Group" },
{ ID: 1, Name: "Patient Administration" },
{ ID: 2, Name: "Medical Charts" },
{ ID: 3, Name: "Medical Procedures" },
{ ID: 13, Name: "Purchase" },
{ ID: 14, Name: "Sales" },
{ ID: 5, Name: "Insurance" },
{ ID: 4, Name: "Cash" },
{ ID: 6, Name: "Pharmacy" },
{ ID: 7, Name: "Inventory" },
{ ID: 8, Name: "Lab" },
{ ID: 9, Name: "Imaging" },
{ ID: 10, Name: "In Patient" },
{ ID: 11, Name: "System Administration" },
{ ID: 12, Name: "Accounting" },
];
const getMatchedobjects = () => {
let result = [0, 1, 2, 3, 4];
let matchedArray = arrDashboardIconGroups.filter((val) => {
const returnResult = result.find((items) => items == val.ID);
console.log(returnResult);
return returnResult;
// result.includes(val.ID)
});
console.log(matchedArray);
};
getMatchedobjects();
Alternatively, you can use includes
let arrDashboardIconGroups = [
{ ID: 0, Name: "General Group" },
{ ID: 1, Name: "Patient Administration" },
{ ID: 2, Name: "Medical Charts" },
{ ID: 3, Name: "Medical Procedures" },
{ ID: 13, Name: "Purchase" },
{ ID: 14, Name: "Sales" },
{ ID: 5, Name: "Insurance" },
{ ID: 4, Name: "Cash" },
{ ID: 6, Name: "Pharmacy" },
{ ID: 7, Name: "Inventory" },
{ ID: 8, Name: "Lab" },
{ ID: 9, Name: "Imaging" },
{ ID: 10, Name: "In Patient" },
{ ID: 11, Name: "System Administration" },
{ ID: 12, Name: "Accounting" },
];
const getMatchedobjects = () => {
let result = [0, 1, 2, 3, 4];
let matchedArray = arrDashboardIconGroups.filter((val) => result.includes(val.ID));
console.log(matchedArray);
};
getMatchedobjects();
Issue
Find returns a value/object (the first matching), but it seems you want to filter the arrDashboardIconGroups array by those that match an id specified in the result array. When result[0] is returned, 0 is the value, which is falsey, and the filter doesn't return the element from the arrDashboardIconGroups array.
Solution
Use Array.prototype.some to return the boolean that filter needs to include an element in the result array.
let arrDashboardIconGroups = [
{ ID:0, Name: 'General Group' },
{ ID: 1, Name: 'Patient Administration' },
{ ID: 2, Name: 'Medical Charts' },
{ ID: 3, Name: 'Medical Procedures' },
{ ID: 13, Name: 'Purchase' },
{ ID: 14, Name: 'Sales' },
{ ID: 5, Name: 'Insurance' },
{ ID: 4, Name: 'Cash' },
{ ID: 6, Name: 'Pharmacy' },
{ ID: 7, Name: 'Inventory' },
{ ID: 8, Name: 'Lab' },
{ ID: 9, Name: 'Imaging' },
{ ID: 10, Name: 'In Patient' },
{ ID: 11, Name: 'System Administration' },
{ ID: 12, Name: 'Accounting' }
];
const getMatchedobjects = () => {
let result = [0,1,2,3,4,];
let matchedArray = arrDashboardIconGroups.filter(val => result.some((items)=>items == val.ID));
console.log(matchedArray);
}
getMatchedobjects();
Alternatively you could also check that result array includes the matching id.
let arrDashboardIconGroups = [
{ ID:0, Name: 'General Group' },
{ ID: 1, Name: 'Patient Administration' },
{ ID: 2, Name: 'Medical Charts' },
{ ID: 3, Name: 'Medical Procedures' },
{ ID: 13, Name: 'Purchase' },
{ ID: 14, Name: 'Sales' },
{ ID: 5, Name: 'Insurance' },
{ ID: 4, Name: 'Cash' },
{ ID: 6, Name: 'Pharmacy' },
{ ID: 7, Name: 'Inventory' },
{ ID: 8, Name: 'Lab' },
{ ID: 9, Name: 'Imaging' },
{ ID: 10, Name: 'In Patient' },
{ ID: 11, Name: 'System Administration' },
{ ID: 12, Name: 'Accounting' }
];
const getMatchedobjects=()=> {
let result = [0,1,2,3,4,];
let matchedArray = arrDashboardIconGroups.filter(val => result.includes(val.ID)) ;
console.log(matchedArray);
}
getMatchedobjects();
find() returns value of the first element in the provided array that satisfies the provided testing function. Since 0 is a falsy value, it does not include it in the final array. See MDN Docs
You can map the result array, and use arrDashboardIconGroups's find function, and return the matching objects.
let arrDashboardIconGroups = [
{ ID: 0, Name: 'General Group' },
{ ID: 1, Name: 'Patient Administration' },
{ ID: 2, Name: 'Medical Charts' },
{ ID: 3, Name: 'Medical Procedures' },
{ ID: 13, Name: 'Purchase' },
{ ID: 14, Name: 'Sales' },
{ ID: 5, Name: 'Insurance' },
{ ID: 4, Name: 'Cash' },
{ ID: 6, Name: 'Pharmacy' },
{ ID: 7, Name: 'Inventory' },
{ ID: 8, Name: 'Lab' },
{ ID: 9, Name: 'Imaging' },
{ ID: 10, Name: 'In Patient' },
{ ID: 11, Name: 'System Administration' },
{ ID: 12, Name: 'Accounting' }
]
const getMatchedobjects=()=> {
let result = [0, 1,2,3,4,99] //99 for trial
let matchedArray = result.map((res)=>arrDashboardIconGroups.find((val)=>val.ID == res)).filter(Boolean);
console.log(matchedArray)
}
getMatchedobjects()

How to get list of parents id in json object

My nested json array looks like:
[
{
id: 1,
name: "Mike",
children: [
{ id: 2, name: "MikeC1" },
{ id: 3, name: "MikeC2" },
{
id: 4, name: "MikeC3",
children: [{ id: 5, name: "MikeCC1" }]
},
]
},
{
id: 6,
name: "Json",
children: [
{ id: 7, name: "JsonC1" },
{ id: 8, name: "JsonC2" },
{
id: 9, name: "JsonC3",
children: [{ id: 10, name: "JsonCC1" },{ id: 11, name: "JsonCC2" }]
},
]
}
]
Now I get a id like "11"
then get the parent ids array in json like [6,9,11]
How to do?
var id = 11
console.log(findParent(id))
//result is [6,9,11]
You need to do recursive search
const persons = [
{
id: 1,
name: "Mike",
children: [
{ id: 2, name: "MikeC1" },
{ id: 3, name: "MikeC2" },
{
id: 4, name: "MikeC3",
children: [{ id: 5, name: "MikeCC1" }]
},
]
},
{
id: 6,
name: "Json",
children: [
{ id: 7, name: "JsonC1" },
{ id: 8, name: "JsonC2" },
{
id: 9, name: "JsonC3",
children: [{ id: 10, name: "JsonCC1" },{ id: 11, name: "JsonCC2" }]
},
]
}
];
function searchRecursive(items, id) {
const allIds = [];
items.forEach(item => {
if(item.id === id) {
allIds.push(item.id);
}
else if(item.children) {
const ids = searchRecursive(item.children, id);
if(ids.length) allIds.push(item.id);
ids.forEach(id => allIds.push(id));
}
});
return allIds;
}
console.log(searchRecursive(persons, 11));

How to convert array of objects into custom grouped array

I am trying to convert the data object to custom format
This is my data which i want to convert
[
{ Name: 15, GroupID: 1, Id: 1 },
{ Name: 16, GroupID: 1, Id: 1 },
{ Name: 17, GroupID: 2, Id: 2 },
{ Name: 18, GroupID: 2, Id: 2 },
{ Name: 15, GroupID: 3, Id: 3 },
{ Name: 16, GroupID: 3, Id: 3 },
{ Name: 17, GroupID: 4, Id: 4 },
{ Name: 18, GroupID: 4, Id: 4 }
];
This is what i want to acheive
{ GroupID: 1 },
{ Name: 15, Id: 1 },
{ Name: 16, Id: 1 },
{ GroupID: 2 },
{ Name: 17, Id: 2 },
{ Name: 18, Id: 2 },
{ GroupID: 3 },
{ Name: 15, Id: 3 },
{ Name: 16, Id: 3 },
{ GroupID: 4 },
{ Name: 17, Id: 4 },
{ Name: 18, Id: 4 }
This is what i have tried till now
var data = [
{ Name: 15, GroupID: 1, Id: 1 },
{ Name: 16, GroupID: 1, Id: 1 },
{ Name: 17, GroupID: 2, Id: 2 },
{ Name: 18, GroupID: 2, Id: 2 },
{ Name: 15, GroupID: 3, Id: 3 },
{ Name: 16, GroupID: 3, Id: 3 },
{ Name: 17, GroupID: 4, Id: 4 },
{ Name: 18, GroupID: 4, Id: 4 }
];
var previousGroupId;
var newObject = new Object();
for (index in data) {
var groupId = data[index].GroupID;
if (groupId != previousGroupId) {
var newGroup = "GroupId" + groupId;
newObject[newGroup] = new Array();
for (index in data) {
if (data[index].GroupID == groupId) {
var customObject = {
"GroupID": groupId,
"Name": data[index].Name,
"Id": data[index].Id
};
newObject[newGroup].push(customObject);
}
}
}
previousGroupId = groupId;
}
console.log(newObject);
even i tried to refer this
Javascript group objects by property
any suggestions would be helpful.
Assuming an array of objects as result set, you could take a hash table with arrays and take a flat array as result set.
var data = [{ Name: 15, GroupID: 1, Id: 1 }, { Name: 16, GroupID: 1, Id: 1 }, { Name: 17, GroupID: 2, Id: 2 }, { Name: 18, GroupID: 2, Id: 2 }, { Name: 15, GroupID: 3, Id: 3 }, { Name: 16, GroupID: 3, Id: 3 }, { Name: 17, GroupID: 4, Id: 4 }, { Name: 18, GroupID: 4, Id: 4 }],
result = Object
.values(data.reduce((r, { Name, GroupID, Id }) => {
r[GroupID] = r[GroupID] || [{ GroupID }];
r[GroupID].push({ Name, Id });
return r;
}, {}))
.flat();
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories

Resources