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

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)

Related

How can I get the result from arr1 and arr2, When the ID matches I need to copy the content from arr1

How can I get the result from arr1 and arr2, When the ID matches I need to copy the content from arr1
const arr1 = [
{ id: 1, name: "omar" },
{ id: 2, name: "laith" },
{ id: 3, name: "aref" },
]
const arr2 = [
{ id: 1, rating: "good" },
{ id: 2, rating: "very good" },
{ id: 2, rating: "very good" },
{ id: 3, rating: "Excellence" },
{ id: 3, rating: "Excellence" },
]
//expected output
const result = [
{ id: 1, rating: "good", name: "omar" },
{ id: 1, rating: "good", name: "omar" },
{ id: 2, rating: "very good", name: "laith" },
{ id: 3, rating: "Excellence", name: "aref" },
{ id: 3, rating: "Excellence", name: "aref" },
]
use reduce with filter
const arr1 = [ { id: 1, name: "omar" }, { id: 2, name: "laith" }, { id: 3, name: "aref" }, ];
const arr2 = [ { id: 1, rating: "good" }, { id: 2, rating: "very good" }, { id: 2, rating: "very good" }, { id: 3, rating: "Excellence" }, { id: 3, rating: "Excellence" }, ];
const result = arr1.reduce((acc,item) => {
const list = arr2.filter(i => i.id === item.id)
return [...acc, ...list.map(i => ({id: i.id,rating:i.rating, name: item.name}))]
}, [])
console.log(result)
Basically with a loop. Actually 2. Using a temporary object (result) as dictionary (or map) we can make it efficient searching for a match to each id. This is of complexity O(n) basically.
const arr1 = [ { id: 1, name: "omar" }, { id: 2, name: "laith" }, { id: 3, name: "aref" }, ];
const arr2 = [ { id: 1, rating: "good" }, { id: 2, rating: "very good" }, { id: 2, rating: "very good" }, { id: 3, rating: "Excellence" }, { id: 3, rating: "Excellence" }, ];
var result = {}
arr1.forEach(function(item1) {
result[item1.id] = item1;
});
arr2.forEach(function(item2) {
result[item2.id] = (result[item2.id] || item2)
result[item2.id]['rating'] = item2.rating
})
result = Object.values(result)
console.log(result)

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));

filter array of object from another array with multiple elements in javascript

I have object and an array:
const response = [
{ id: 1, product: 'EL' },
{ id: 2, product: 'AC' },
{ id: 3, product: 'AC' },
{ id: 4, product: 'AD' },
{ id: 5, product: 'DE' },
];
const elProd = [
"EL"
"DE"
];
i want to filter out the product which has product code in elProd array.
my expectation is below:
const response = [
{ id: 2, product: 'AC' },
{ id: 3, product: 'AC' },
{ id: 4, product: 'AD' },
];
what I tried :
response.filter(obj => {return obj.product == elProd .includes(obj.product)})
const response = [{
id: 1,
product: 'EL'
},
{
id: 2,
product: 'AC'
},
{
id: 3,
product: 'AC'
},
{
id: 4,
product: 'AD'
},
{
id: 5,
product: 'DE'
},
];
const elProd = [
"EL",
"DE"
];
const filteredresp = response.filter((resp) => elProd.indexOf(resp.product) !== -1);
console.log(filteredresp);
response.filter(obj => {return !elProd.includes(obj.product)});
You almost got it, but you have a typo. You need a comma in the elProd array. Here's the code:
const response = [
{ id: 1, product: "EL" },
{ id: 2, product: "AC" },
{ id: 3, product: "AC" },
{ id: 4, product: "AD" },
{ id: 5, product: "DE" },
];
const elProd = [
"EL", // <-- Add the comma.
"DE",
];
// Don't forget to negate the includes here to exclude those you don't want.
const filtered = response.filter((obj) => !elProd.includes(obj.product));
// Result.
console.log(filtered);
You need only the check with includes.
const
response = [{ id: 1, product: 'EL' }, { id: 2, product: 'AC' }, { id: 3, product: 'AC' }, { id: 4, product: 'AD' }, { id: 5, product: 'DE' }],
elProd = ["EL", "DE"],
result = response.filter(obj => !elProd.includes(obj.product));
console.log(result);
You could use filter and some
const response = [
{ id: 1, product: 'EL' },
{ id: 2, product: 'AC' },
{ id: 3, product: 'AC' },
{ id: 4, product: 'AD' },
{ id: 5, product: 'DE' },
];
const elProd = [
"EL",
"DE"
]
res=response.filter(o=>!elProd.some(p=>o.product==p))
console.log(res)

Typescript - Rearrange specific object

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; }

Categories

Resources