Searching values in array of objects /Javascript - javascript

Consider the following arrays of objects :
[{ id: 5, name: "Spain"},
{ id: 6, name: "Denmark"},
{ id: 7, name: "USA"},
{ id: 8, name: "Iceland"},
{ id: 9, name: "Greece"},
{ id: 10, name: "UK"},
{ id: 11, name: "Germany"},
{ id: 12, name: "Italy"}]
[{ id: 13, name: "US"},
{ id: 14, name: "GR"},
{ id: 15, name: "ESP"},
{ id: 16, name: "ICEL"},
{ id: 17, name: "DEN"},
{ id: 18, name: "UK"},
{ id: 19, name: "IT"},
{ id: 20, name: "GER"}]
I want to search through the first array and find the respective match for the second array. Or even better get one element from the second array and search for it against all the values in the first array .
EX. GER = { id: 11, name: "Germany"}
IT = { id: 12, name: "Italy"}
Is there a best practise for implementing this kind of search ?

If you are looking for a data structure, you could use an object with the reference to the objects of the first array.
You need to implement it by hand as long as you do not have a relation of the matching id.
countries = {
ESP: { id: 5, name: "Spain"},
DEN: { id: 6, name: "Denmark"},
US: { id: 7, name: "USA"},
ICEL: { id: 8, name: "Iceland"},
GR: { id: 9, name: "Greece"},
UK: { id: 10, name: "UK"},
GER: { id: 11, name: "Germany"},
IT: { id: 12, name: "Italy"}
}
Access via
countries.ICEL.name // Iceland
or
country = 'GR'
countries[country].name // Greece

Related

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 would I compare the two to properly sort in order?

Objective is to distinguish the two arrays, and console log the products array in order by its price range, I tried using a nested for-loop to see if this can work out but hasn't gone off in the right track, was also thinking about using lo dash as well. How would I be able to compare the id's between the two and push them in order by price?
/*
Your task is to write a function or set of functions that console logs out the products ordered by price
*/
var products = [
{ id: 1, name: 'Buzzy' },
{ id: 2, name: 'Bytrex' },
{ id: 3, name: 'CactiDance' },
{ id: 4, name: 'CactiLoops' },
{ id: 5, name: 'Cadaver Jelly' },
{ id: 6, name: 'Caffeine Serene' },
{ id: 7, name: 'Cajun Sation' },
{ id: 8, name: 'Call it Green' },
{ id: 9, name: 'Callflex' },
{ id: 10, name: 'Calling Card Shark' },
{ id: 11, name: 'Calque' },
{ id: 12, name: 'Camel Meal Tea' },
{ id: 13, name: 'Camelot Chamomile' },
{ id: 14, name: 'Campxotica' },
{ id: 15, name: 'Camus the Killer Tale' },
{ id: 16, name: 'Candecor' },
{ id: 17, name: 'Candelarium' },
{ id: 18, name: 'CandID' },
{ id: 19, name: 'Candlelight Vittles' },
{ id: 20, name: 'Candy Ask' },
{ id: 21, name: 'Candy Floss' },
];
var prices = [
{ id: 6, price: 55 },
{ id: 14, price: 22 },
{ id: 15, price: 57 },
{ id: 4, price: 41 },
{ id: 18, price: 9 },
{ id: 17, price: 3 },
{ id: 2, price: 73 },
{ id: 7, price: 43 },
{ id: 5, price: 78 },
{ id: 1, price: 91 },
{ id: 8, price: 58 },
{ id: 16, price: 69 },
{ id: 13, price: 74 },
{ id: 19, price: 14 },
{ id: 21, price: 25 },
{ id: 12, price: 84 },
{ id: 20, price: 8 },
{ id: 9, price: 94 },
{ id: 10, price: 36 },
{ id: 3, price: 34 },
{ id: 11, price: 71 },
];
You can use map & findIndex. map will return a new array. Inside the callback function of map use findIndex and use it to find the index of the object where the id matches.
var products = [{
id: 1,
name: 'Buzzy'
},
{
id: 2,
name: 'Bytrex'
},
{
id: 3,
name: 'CactiDance'
},
{
id: 4,
name: 'CactiLoops'
},
{
id: 5,
name: 'Cadaver Jelly'
},
{
id: 6,
name: 'Caffeine Serene'
},
{
id: 7,
name: 'Cajun Sation'
},
{
id: 8,
name: 'Call it Green'
},
{
id: 9,
name: 'Callflex'
},
{
id: 10,
name: 'Calling Card Shark'
},
{
id: 11,
name: 'Calque'
},
{
id: 12,
name: 'Camel Meal Tea'
},
{
id: 13,
name: 'Camelot Chamomile'
},
{
id: 14,
name: 'Campxotica'
},
{
id: 15,
name: 'Camus the Killer Tale'
},
{
id: 16,
name: 'Candecor'
},
{
id: 17,
name: 'Candelarium'
},
{
id: 18,
name: 'CandID'
},
{
id: 19,
name: 'Candlelight Vittles'
},
{
id: 20,
name: 'Candy Ask'
},
{
id: 21,
name: 'Candy Floss'
},
];
var prices = [{
id: 6,
price: 55
},
{
id: 14,
price: 22
},
{
id: 15,
price: 57
},
{
id: 4,
price: 41
},
{
id: 18,
price: 9
},
{
id: 17,
price: 3
},
{
id: 2,
price: 73
},
{
id: 7,
price: 43
},
{
id: 5,
price: 78
},
{
id: 1,
price: 91
},
{
id: 8,
price: 58
},
{
id: 16,
price: 69
},
{
id: 13,
price: 74
},
{
id: 19,
price: 14
},
{
id: 21,
price: 25
},
{
id: 12,
price: 84
},
{
id: 20,
price: 8
},
{
id: 9,
price: 94
},
{
id: 10,
price: 36
},
{
id: 3,
price: 34
},
{
id: 11,
price: 71
},
];
let newArr = prices.map(function(item) {
let k = products.findIndex(elem => elem.id === item.id);
if (k !== -1) {
return products[k]
}
});
console.log(newArr)
You could sort the prices array first. Then loop through it and get the products for each id using find like this:
var products = [{id:1,name:"Buzzy"},{id:2,name:"Bytrex"},{id:3,name:"CactiDance"},{id:4,name:"CactiLoops"},{id:5,name:"Cadaver Jelly"},{id:6,name:"Caffeine Serene"},{id:7,name:"Cajun Sation"},{id:8,name:"Call it Green"},{id:9,name:"Callflex"},{id:10,name:"Calling Card Shark"},{id:11,name:"Calque"},{id:12,name:"Camel Meal Tea"},{id:13,name:"Camelot Chamomile"},{id:14,name:"Campxotica"},{id:15,name:"Camus the Killer Tale"},{id:16,name:"Candecor"},{id:17,name:"Candelarium"},{id:18,name:"CandID"},{id:19,name:"Candlelight Vittles"},{id:20,name:"Candy Ask"},{id:21,name:"Candy Floss"}],
prices = [{id:6,price:55},{id:14,price:22},{id:15,price:57},{id:4,price:41},{id:18,price:9},{id:17,price:3},{id:2,price:73},{id:7,price:43},{id:5,price:78},{id:1,price:91},{id:8,price:58},{id:16,price:69},{id:13,price:74},{id:19,price:14},{id:21,price:25},{id:12,price:84},{id:20,price:8},{id:9,price:94},{id:10,price:36},{id:3,price:34},{id:11,price:71}];
prices.sort((a, b) => a.price - b.price)
.forEach(p => {
console.log(products.find(a => a.id === p.id))
})

How to add object element in array based on condition

I have static array constant of objects something similar to below.
export const EMPLOYEES = [
{
id: 2,
name: ‘John’,
},
{
id: 3,
name: ‘Doe’,
},
{
id: 4,
name: ‘Bull’,
},
{
id: 5,
name: ‘Scott’,
},
];
Now I need to add the last element only based on if some condition is true. Some this like if isAmerican() is true.
Can somebody help me here how to add element based on the condition? Thanks.
You can do it using spread operator:
export const EMPLOYEES = [
{
id: 2,
name: "John",
},
{
id: 3,
name: "Doe",
},
{
id: 4,
name: "Bull",
},
{
id: 5,
name: "Scott",
},
... isAmerican() ? [{ id: 6, name: "Jemmy"}] : []
];
You should never modify (or try to modify) a constant. I can see two ways you can do this:
Create a pure function to return a new constant with the new object added to the array
Use a spread operator in the definition of the constant
Option 1: Pure function
function makeNewArray(array, objectToAppend, isAmerican) {
return isAmerican ? [...array, objectToAppend] : array
}
const EMPLOYEES = [
{
id: 2,
name: "John",
},
{
id: 3,
name: "Doe",
},
{
id: 4,
name: "Bull",
},
{
id: 5,
name: "Scott",
}
];
const arrayWithAmerican = makeNewArray(EMPLOYEES, { id: 6, name: "American Frank"}, true);
const arrayWithoutAmerican = makeNewArray(EMPLOYEES, { id: 6, name: "Not American Frank"}, false);
console.log(arrayWithAmerican);
console.log(arrayWithoutAmerican);
Option 2: Spread operator
function isAmerican(){
// generic code here.
return true;
}
const EMPLOYEES = [
{
id: 2,
name: "John",
},
{
id: 3,
name: "Doe",
},
{
id: 4,
name: "Bull",
},
{
id: 5,
name: "Scott",
},
... isAmerican() ? [{ id: 6, name: "American Frank"}] : []
];
If the condition will be fulfilled, simply push an object to your EMPLOYEES array:
let isAmerican = true;
const EMPLOYEES = [
{
id: 2,
name: "John",
},
{
id: 3,
name: "Doe",
},
{
id: 4,
name: "Bull",
},
{
id: 5,
name: "Scott",
},
];
if(isAmerican) {
EMPLOYEES.push({
id: 6,
name: "Frank"
})
}
console.log(EMPLOYEES)
Fiddle: https://jsfiddle.net/rqx35pLz/

Sort a flat list by parent id with lodash

I have a JSON list of objects with an id, name and reference to parent id :
const myList = [
{
id: 1,
name: "name1",
parentId: null
},
{
id: 5,
name: "name5",
parentId: 32
},
{
id: 32,
name: "name32",
parentId: 48
},
{
id: 48,
name: "name48",
parentId: 1
}
]
I would like to sort that list hierarchically, depending on the parent id :
[
{
id: 1,
name: "name1",
parentId: null
},
{
id: 48,
name: "name48",
parentId: 1
},
{
id: 32,
name: "name32",
parentId: 48
},
{
id: 5,
name: "name5",
parentId: 32
}
]
I'm new in Javascript programming and lodash, and I was wondering if there is an easy way to sort that list with lodash ?
Thank you in advance.
Benj
I found a solution with lodash.
Not sure it's the best but it works.
var parentId = null;
var sortedList = [];
var byParentsIdsList = _.groupBy(myList, "parentId"); // Create a new array with objects indexed by parentId
while (byParentsIdsList[parentId]) {
sortedList.push(byParentsIdsList[parentId][0]);
parentId = byParentsIdsList[parentId][0].id;
}
You can use lodash's method sortBy
var sorted = _.sortBy(myList, "parentId");
console.log(sorted);
/* OUTPUT
[
{
id: 1,
name: "name1",
parentId: null
},
{
id: 48,
name: "name48",
parentId: 1
},
{
id: 5,
name: "name5",
parentId: 32
},
{
id: 32,
name: "name32",
parentId: 48
}
]
*/
https://jsfiddle.net/L88t09ne/
with vanilla js [].sort() method:
const myList = [
{
id: 1,
name: "name1",
parentId: null
},
{
id: 5,
name: "name5",
parentId: 32
},
{
id: 32,
name: "name32",
parentId: 48
},
{
id: 48,
name: "name48",
parentId: 1
}
];
var arr = myList.sort(function(a,b){
return a.parentId -b.parentId
});
console.log(arr)

Categories

Resources