Match array value with value in an array of objects javascript - javascript

I am trying to work out how I can return a list with values from the own key in the array bellow if the object name value matches values in the lookupvalues array
lookupvalues = ["ross","linda"]
resources = [{own: "car", name: "bob"},{own: "bike", name: "ross"},{own: "plane", name: "linda"}]
wanted_output = ["bike","plane"]
I am struggling a bit with a good method to use for when I need to compare value in an object with array values. Is there a reasonable straight forward way to do this?
I must say how impressed I am that I got 4 replies with working examples at the same time!

One way (array method chaining) is that you could filter by name and map to grap each's own
const lookupvalues = ["ross", "linda"]
const resources = [
{ own: "car", name: "bob" },
{ own: "bike", name: "ross" },
{ own: "plane", name: "linda" },
]
const res = resources
.filter(({ name }) => lookupvalues.includes(name))
.map(({ own }) => own)
console.log(res)

resources.filter(resource => lookupvalues.includes(resource.name))
.map(resource => resource.own);
This will filter by the items that have names that are included in lookupvalues, and then transform the array into an array of the own values of those remaining.

You can take the help of Array#filter and Array#map:
const lookupvalues = ["ross","linda"]
const resources = [{own: "car", name: "bob"},{own: "bike", name: "ross"},{own: "plane", name: "linda"}]
const filterRes = (arr) => {
const lookup = new Set(lookupvalues);
return arr.filter(({name}) => lookup.has(name))
.map(({own}) => own);
}
console.log(filterRes(resources));

resources.filter(item => lookupvalues.indexOf(item.name) > -1).map(item => item.own)

Related

How to improve nested object arrays lookup

Is there a common known way to chain .map or .filter or .find expressions to accomplish this kind of lookup?
Given and array of objects within an array of objects
customerGroups :
[
{
id: 1,
customers: [{
id: 1, // The same customer may appear in multiple groups
name: 'Jhon'
}],
},
{
id: 2,
customers: [{
id: 2,
name: 'Jhon'
}],
},
{
id: 3,
customers: [{
id: 2,
name: 'Doe'
}],
},
]
In the use case where you have the customer.id and want to find out the customer.name I would like to extract the customers array to use the Array.Find method
const idSearch = 1
const customerName = customers.find(({id})=>id==idSearch).name
So far I been trying with
const customers = customerGroup.find(({ customer }) =>
customer.find(({ id }) =>idSearch === id),
)?.customers
const customerName = customers.find(({id})=>id==idSearch).name
I believe there is a better way to do this but I'm too burnout to figure it out.
I've also tried some shenanigans with the .map to make a new array with all the customers in it but no good results so far.
I could also fetch that array from my Backend but I already have all the customers in memory so that would be an overheat.
There is not one native method that does this, but you could first combine the customer arrays into one with flatMap, and then use find:
const customerGroups = [{id:1,customers:[{id:1,name:'Jhon'}]},{id:2,customers:[{id:2,name:'Jhon'}]},{id:3,customers:[{id:2,name: 'Doe'}]}];
const idSearch = 1;
const allCustomers = customerGroups.flatMap(({customers}) => customers);
const name = allCustomers.find(({id}) => id === idSearch)?.name;
console.log(name);
This approach works because as soon as the inside find loop discovers a result, both the inside and outside loop will terminate, leaving name set as the match which caused the loops to terminate (or as undefined if no match was found).
const d = [{id:1,customers:[{id:1,name:'Jhon'}]},{id:2,customers:[{id:2,name:'Jhon'}]},{id:3,customers:[{id:3,name: 'Doe'}]}]
const idSearch = 1
let name
d.find(j=>j.customers.find(i=>i.id===idSearch && ({name}=i)))
console.log(name)

JS - How to add key:value pairs from objects nested in arrays to other objects nested in another array

I know it has been countlessly asked and I assure you that I've read a lot of posts, articles, etc., and watched a lot of videos but nothing seems to click.
so there we go :
Here are 2 arrays with partial information about every person
let arr1 = [{id:00, name:Ben, city:Philadelphia}, {id:01, name:Alice, city:Frankfurt}, {id:02, name:Detlef, city:Vienna}]
let arr2 = [{id:02, age:18}, {id:00, age:39}, {id:01, age:75}]
And there is the desired final result: an array including the name, city, and age of each person
let arr3 = [{name:Ben, city:Philadelphia, age:39}, {name:Alice, city:Frankfurt, age:75 }, {name:Detlef, city:Vienna, age:18}]
What's the situation? Two arrays both containing objects. each nested object has an id. That id is the common key in each array of objects.
What do you want to do? : I want to create a third array including information from both arrays (from arr1: name and city; from arr2:age).
What have you tried so far? : I couldn't manage to achieve anything worth showing. this minimal example is intended to show you a simple example of my current situation which is: I've got an array that is in the LocalStorage on one hand and an API on the other, both contain some info regarding particular objects (let's say, persons). I want to create an array that will contain all the information regarding each person for easier manipulation afterward (DOM generation, etc.).
I've managed to store both arrays in two "local" arrays but the problem is still there: I can't figure out how to make an array where items are getting their key/value from two separate sources.
Thank you for your help!
You can use reduce method on the arr with array as an inital value, and inside try to find the corrospending item with same id and destruct the object from the id and merge the two object with spread operator.
let arr1 = [{id:00, name:'Ben', city: 'Philadelphia' }, {id:01, name:'Alice', city:'Frankfurt'}, {id:02, name:'Detlef', city:'Vienna'}]
let arr2 = [{id:02, age:18}, {id:00, age:39}, {id:01, age:75}]
const result = arr1.reduce((acc, { id: id1, ...rest1 }) => {
const { id: id2, ...rest2 } = arr2.find(i => i.id === id1)
acc.push({ ...rest1, ...rest2 })
return acc;
}, [])
console.log(result)
You can solve it in various ways, here first I have implemented a dict with key as id to get the value in O(1) while iterating arr2.
So the overall time complexity is O(n+k) where n is len of arr1 and k is len of arr2.
let arr1 = [{id:00, name: "Ben", city: "Philadelphia"}, {id:01, name:"Alice", city:"Frankfurt"}, {id:02, name:"Detlef", city:"Vienna"}];
let arr2 = [{id:02, age:18}, {id:00, age:39}, {id:01, age:75}];
const refMapById = arr1.reduce((refMap, {id, name, city}) => {
refMap[id] = {name, city};
return refMap;
}, {});
const result = arr2.reduce((resultArray, {id, age}) => [...resultArray, { ...refMapById[id],age}], []);
console.log(result);
Cheers!
It will be worth creating a dictionary from one of the arrays anyway since using .find() inside of .reduce() adds an unnecessary nested loop. But instead of reducing the second array as was suggested you can simply .map() it into the result array, like so:
let arr1 = [{ id: 00, name: "Ben", city: "Philadelphia" }, { id: 01, name: "Alice", city: "Frankfurt" }, { id: 02, name: "Detlef", city: "Vienna" }];
let arr2 = [{ id: 02, age: 18 }, { id: 00, age: 39 }, { id: 01, age: 75 }];
const groupedById = arr1.reduce((group, person) => {
group[person.id] = person;
return group;
}, {});
const result = arr2.map((personPartFromSecondArray) => {
const personPartFromFirstArray = groupedById[personPartFromSecondArray.id];
if (typeof personPartFromFirstArray !== "undefined") {
return { ...personPartFromFirstArray, ...personPartFromSecondArray }
}
return personPartFromSecondArray;
});
console.log(result);

Remove objects from array where an attribute is equal to specific string

I am using an array.filter() function to remove all the objects where one of their attribute is equal to any of the string in a given array.
The objects in the array are crypto trades and I need to filter out the trades with the trade pairs that I do not want. How would I achieve this using the filter function?
For now, I tried this which did not work evidently:
filteredPairs = filteredPairs.filter(
(pair) =>
!pair.symbol.includes(
"USDTBUSD",
"USDTUSDC",
"USDTUST",
"USDTUSDP",
"USDTDAI",
"BUSDUSDT",
"BUSDUSDC",
"BUSDUST",
"BUSDUSDP",
"BUSDDAI",
"USDCUSDT",
"USDCBUSD",
"USDCUST",
"USDCUSDP",
"USDCDAI",
"USTUSDT",
"USTBUSD",
"USTUSDC",
"USTUSDP",
"USTDAI",
"USDPUSDT",
"USDPBUSD",
"USDPUSDC",
"USDPUST",
"USDPDAI",
"DAIUSDT",
"DAIBUSD",
"DAIUSDC",
"DAIUSDP",
"DATUST"
)
);
This is not filtering out these pairs. Any insight would be helpful. Thank you.
This can be done in a single line.
// testing object
const filteredPairs = [
{
symbol: 'USDTBUSD',
},
{
symbol: 'abc',
},
{
symbol: 'BUSDUSDT',
},
{
symbol: '321',
},
];
// items we don't want
const blacklist = [
'USDTBUSD',
'USDTUSDC',
'USDTUST',
'USDTUSDP',
'USDTDAI',
'BUSDUSDT',
'BUSDUSDC',
'BUSDUST',
'BUSDUSDP',
'BUSDDAI',
'USDCUSDT',
'USDCBUSD',
'USDCUST',
'USDCUSDP',
'USDCDAI',
'USTUSDT',
'USTBUSD',
'USTUSDC',
'USTUSDP',
'USTDAI',
'USDPUSDT',
'USDPBUSD',
'USDPUSDC',
'USDPUST',
'USDPDAI',
'DAIUSDT',
'DAIBUSD',
'DAIUSDC',
'DAIUSDP',
'DATUST',
];
// filter
const newFilteredPairs = filteredPairs.filter(({ symbol }) => !blacklist.some((item) => symbol.includes(item)));
console.log(newFilteredPairs);

I have two arrays, with the same values in the first array as in the ID fields of the second array

What I want to achieve is to have a third array with an output seen at the bottom from two other arrays.
Now the key here is that it is basically a filter based on the Object.keys array matches from the mapped array. Meaning any id that exists in the mapped array and the Object.keys array should go into the third array.
The more I think about the more it seems I need to do a filter on the mapped array, just not 100% certain how to achieve that properly. I did just try a filter now seen below and it returns an empty array.
I have also tried using a findIndex to find the matching id's but it doesn't seem to find matches.
Any help would be greatly appreciated
Thanks Kindly
const mapped = data.allProduct.map((item: any) => ({
slug: item.slug.current,
id: item.stripeId,
}));
// What I have tried
const foundMapped = mapped.findIndex(
(element: any, index: any) => element.id === Object.keys(cartDetails)[index]
);
const test = mapped.filter(
(item: any, index: any) => item.id === Object.keys(cartDetails)[index]
);
this is Object.keys(cartDetails)
[
"price_1KhMhhF2lAt0poJW42giHxDs",
"price_1KVisMF2lAt0poJWnd9LGheT",
"price_1KVisMF2lAt0poJWnd9fkfkf",
]
this is variable mapped from above
[
{
"slug": "the-void",
"id": "price_1KVisMF2lAt0poJWnd9LGheT"
},
{
"slug": "magic-wonders-artwork",
"id": "price_1KhMhhF2lAt0poJW42giHxDs"
},
{
"slug": "other-two",
"id": "price_1KVisMF2lAt0poJWnd9fkfkf"
},
{
"slug": "test-test",
"id": "price_1KVisMF2lAt0poJWnd9fjff"
}
]
Third Array Output
[
{
id: "price_1KhMhhF2lAt0poJW42giHxDs",
slug: "the-void"
},
{
id: "price_1KVisMF2lAt0poJWnd9LGheT",
slug: "magic-wonders-artwork"
},
{
id: "price_1KVisMF2lAt0poJWnd9fkfkf",
slug: "other-two"
},
]
just gotta check if the id is in the array of the keys in your filter predicate:
const keys = Object.keys(cartDetails);
const toFilter = data.allProduct.map((item: any) => ({
slug: item.slug.current,
id: item.stripeId,
}));
const filtered = toFilter.filter(i => keys.includes(i.id))
though I'm not sure why you wouldn't just skip the object keys to array mapping and just check the original object, which is more efficient than checking if an item is in an array:
const filtered = toFilter.filter(i => !!cartDetails[i.id])
or
const filtered = toFilter.filter(i => cartDetails[i.id] !== undefined)
if cartDetails can / might include valid falsey values like 0, empty string or false

How to check if property of an objects of array matches with one of the values in another array of object

I know the header is way too complicated but that's how it is right now. Let me make it more clear for you.
There is an object like
const users= [
{
id:"1",
name:"John",
mail:"aaa#gmail.com",
},
{
id:"2",
name:"Joe",
mail:"bbb#gmail.com",
},
]
Then there is
const attendingUsers = [
{
id:"1",
name:"John",
mail:"aaa#gmail.com",
.....
},
{
id:"2",
name:"Joe",
mail:"bbb#gmail.com",
.....
},}
] 
Both of the arrays has different properties and I just want to get the ones that are important to me. What I need is to look through users array and find the ones that has the same ids as the ones from attendingUsers.
I have came up with users.filter(user => user.id == attendingUsers.map(attendingUser => attendingUser.id)); but that is simply returning empty array. Any idea what would be the best way to tackle this sort of a problem?
First off, you'll have to make sure if the ID types are correct. Users has Number type for IDs but attendingUsers has String type.
Let's say they're both the same type for the code below (I'm going with string).
You can turn the attendingUsers array into an array of strings with:
const attendingUsersIds = attendingUsers.map(attendingUser => attendingUser.id)
Then match the ids with:
const matchedUsers = users.filter(user => attendingUsersIds.includes(user.id))
If they're intended to not be the same type, you can use user.id.toString() to turn the Number into a String or parseInt(attendingUser.id) to turn the String into a Number.
We can use Array.map to create a new array of users, with a property isAttending added to each user.
We determine if they are attending by using Array.some to search for any matching attendee with the same id.
const users = [
{
id:1,
name:"John",
mail:"aaa#gmail.com",
},
{
id:2,
name:"Joe",
mail:"bbb#gmail.com",
},
{
id:3,
name:"Alice",
mail:"ccc#gmail.com",
}
]
const attendingUsers = [
{
id:"1",
name:"John",
mail:"aaa#gmail.com",
},
{
id:"2",
name:"Joe",
mail:"bbb#gmail.com",
}
]
const result = users.map(user => {
return { ...user, isAttending: attendingUsers.some(({id}) => id == user.id) };
});
console.log("Users (with attending property):", result);

Categories

Resources