Item search between two array in nodejs - javascript

I have two fixes, where the first fix that is dataMedical has an attribute called safeId and I need it to look for its name in the dataSafe array, they are associated by the id attribute that is safeId.
*Remembering that dataMedical can have N item as well as dataSafe.*
dataMedical = [
{
_id: 5da619b36aae5e7028fc27db,
paciente: 5de31abf4c430918a39a7490,
seguroAfiliado: 5d65da2f008b72055d17abfb,
fecha: '2019-10-01T03:00:00.000Z',
motivoConsulta: 'dww',
__v: 0
}
]
dataSafe = [ { _id: 5d65da2f008b72055d17abfb,
nombre: 'La Seguridad',
email: 'info#laseguridad.com.ve',
numeroPoliza: '123456',
pais: 'fdsaafsd',
baremo: 'afdafds',
actoQuirurgico: 'fsdasafd',
__v: 0 },
{ _id: 5d62c609e7179a084ef359fd,
nombre: 'Mappfre',
email: 'info#mappfre.com',
numeroPoliza: '098765',
actoQuirurgico: 'acto2',
baremo: 'rweq',
pais: 'usa' } ]
I need as a result:
dataMedicalResult = [
{
_id: 5da619b36aae5e7028fc27db,
paciente: 5de31abf4c430918a39a7490,
seguroAfiliado: 5d65da2f008b72055d17abfb,
fecha: '2019-10-01T03:00:00.000Z',
motivoConsulta: 'dww',
nameSafe: 'La Seguridad',
email: 'info#laseguridad.com.ve',
numeroPoliza: '123456',
pais: 'fdsaafsd',
baremo: 'afdafds',
actoQuirurgico: 'fsdasafd',
}
]
Try all code and again and answer me this:
https://ramdajs.com/repl/?v=0.26.1#?%5B%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%22%24__%22%3A%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%22strictMode%22%3A%20true%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%22selected%22%3A%20%7B%7D%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%22getters%22%3A%20%7B%7D%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%22_id%22%3A%20%225da619b36aae5e7028fc27db%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%22wasPopulated%22%3A%20false%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%22activePaths%22%3A%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22paths%22%3A%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22_id%22%3A%20%22init%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22paciente%22%3A%20%22init%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22seguroAfiliado%22%3A%20%22init%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22fecha%22%3A%20%22init%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22motivoConsulta%22%3A%20%22init%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22__v%22%3A%20%22init%22%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22states%22%3A%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22ignore%22%3A%20%7B%7D%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22default%22%3A%20%7B%7D%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22init%22%3A%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22_id%22%3A%20true%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22paciente%22%3A%20true%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22seguroAfiliado%22%3A%20true%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22fecha%22%3A%20true%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22motivoConsulta%22%3A%20true%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22__v%22%3A%20true%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22modify%22%3A%20%7B%7D%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22require%22%3A%20%7B%7D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22stateNames%22%3A%20%5B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22require%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22modify%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22init%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22default%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22ignore%22%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%5D%0A%20%20%20%20%20%20%20%20%20%20%20%20%7D%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%22pathsToScopes%22%3A%20%7B%7D%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%22cachedRequired%22%3A%20%7B%7D%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%22session%22%3A%20null%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%22%24setCalled%22%3A%20%7B%7D%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%22emitter%22%3A%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22_events%22%3A%20%7B%7D%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22_eventsCount%22%3A%200%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22_maxListeners%22%3A%200%0A%20%20%20%20%20%20%20%20%20%20%20%20%7D%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%22%24options%22%3A%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22skipId%22%3A%20true%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22isNew%22%3A%20false%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22willInit%22%3A%20true%0A%20%20%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%7D%2C%0A%20%20%20%20%20%20%20%20%22isNew%22%3A%20false%2C%0A%20%20%20%20%20%20%20%20%22_doc%22%3A%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%22_id%22%3A%20%225da619b36aae5e7028fc27db%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%22paciente%22%3A%20%225de31abf4c430918a39a7490%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%22seguroAfiliado%22%3A%20%225d65da2f008b72055d17abfb%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%22fecha%22%3A%20%222019-10-01T03%3A00%3A00.000Z%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%22motivoConsulta%22%3A%20%22dww%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%22__v%22%3A%200%0A%20%20%20%20%20%20%20%20%7D%2C%0A%20%20%20%20%20%20%20%20%22%24locals%22%3A%20%7B%7D%2C%0A%20%20%20%20%20%20%20%20%22%24init%22%3A%20true%0A%20%20%20%20%7D%0A%5D
Current Answer:
Code modified with values 'safes' and 'citasMedicas':
Result with POSTMAN:

Try this:
console.log(dataSafe.reduce((acc,el)=> {
const dm = dataMedical.find(dam => dam["_id"] === el["_id"]);
return dm ? [...acc, Object.assign(el, dm)] : acc;
}, []))

Would something like this work? it searches for the given id in both arrays and then joins the two found objects
const dataMedical = [{
"_id": "1",
"pacient": "Jhon",
"safeId": "1",
"data": "2019-10-01T03:00:00.000Z",
"consult": "dww",
"__v": 0
}]
const dataSafe = [{
"_id": "1",
"nameSafe": "La Seguridad"
},
{
"_id": "2",
"nameSafe": "Mappfre"
}
]
function findRecord(id) {
const medical = dataMedical.find(r => r._id === id)
const safe = dataSafe.find(r => r._id === id)
return {
...medical,
...safe
}
}
const dataMedicalResult = findRecord("1")
console.log(dataMedicalResult)

You can use the Array find function to locate the correct dataSafe element. We will map over each element in dataMedical, and use the safeId to find the correct dataSafe. Then, we will copy over the nameSafe property to the safe.
let dataMedical = [
{
"_id": "1",
"pacient": "Jhon",
"safeId": "1",
"data": "2019-10-01T03:00:00.000Z",
"consult": "dww",
"__v": 0
}
]
let dataSafe = [
{
"_id": "1",
"nameSafe": "La Seguridad"
},
{
"_id": "2",
"nameSafe": "Mappfre"
}
]
let dataMedicalResult = dataMedical.map(dm => {
let safe = dataSafe.find(e => e._id == dm.safeId);
return safe
? {...dm, nameSafe: safe.nameSafe}
: dm;
})
console.log(dataMedicalResult);
EDIT: It looks like the other answers are not looking at the safeId property to find the correct safe, so this should be the correct solution.

This could help too,
I think trying to make point free results in a more complicate approach...
const mergeWithDataSafe = (merger, data) => merger(
(item) => R.mergeRight(item, R.path([item.safeId, 0], data)),
);
const aggregate = R.useWith(mergeWithDataSafe, [
R.flip(R.map),
R.groupBy(R.prop('_id')),
]);
const dataMedical = [
{
"_id": "1",
"pacient": "Jhon",
"safeId": "1",
"data": "2019-10-01T03:00:00.000Z",
"consult": "dww",
"__v": 0
}
];
const dataSafe = [
{
"_id": "1",
"nameSafe": "La Seguridad"
},
{
"_id": "2",
"nameSafe": "Mappfre"
}
];
console.log(
aggregate(dataMedical, dataSafe),
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js" integrity="sha256-xB25ljGZ7K2VXnq087unEnoVhvTosWWtqXB4tAtZmHU=" crossorigin="anonymous"></script>

You can use R.indexBy to convert the dataSafe array to a dictionary using _id as the key. Now you can map dataMedical and merge with the item with the same safeId from the safeDict:
const { curry, indexBy, prop, merge } = R;
const fn = curry((medical, safe) => {
const safeDict = indexBy(prop('_id'), safe); // convert the safe array to a dictionary with _id as key
return medical.map(o => merge(safeDict[o.safeId], o)); // map medical and merge with object with same _id from safeDict
});
const dataMedical = [{"_id":"1","pacient":"Jhon","safeId":"1","data":"2019-10-01T03:00:00.000Z","consult":"dww","__v":0}];
const dataSafe = [{"_id":"1","nameSafe":"La Seguridad"},{"_id":"2","nameSafe":"Mappfre"}];
const result = fn(dataMedical, dataSafe)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js" integrity="sha256-xB25ljGZ7K2VXnq087unEnoVhvTosWWtqXB4tAtZmHU=" crossorigin="anonymous"></script>
The same idea can be easily used without Ramda - create a Map from dataSafe, and then map dataMedical and get the an item from the safeDict using the safeId, and combine with current medical object using spread:
const fn = (medical, safe) => {
const safeDict = new Map(safe.map(o => [o._id, o])); // convert the safe array to a dictionary with _id as key
return medical.map(o => ({ ...o, ...safeDict.get(o.safeId) })); // map medical and merge with object with same _id from safeDict
};
const dataMedical = [{"_id":"1","pacient":"Jhon","safeId":"1","data":"2019-10-01T03:00:00.000Z","consult":"dww","__v":0}];
const dataSafe = [{"_id":"1","nameSafe":"La Seguridad"},{"_id":"2","nameSafe":"Mappfre"}];
const result = fn(dataMedical, dataSafe);
console.log(result);

I might write it like this:
const enhance = (safe) => (
med,
{_id, ...rest} = safe .find (({_id}) => _id == med.safeId) || {}
) => ({...med, ...rest})
const enhanceAll = (safe) => R.map (enhance (safe))
const dataMedical = [{_id: "1", pacient: "Jhon", safeId: "1", data: "2019-10-01T03:00:00.000Z", consult: "dww", __v: 0}]
const dataSafe = [{_id: "1", nameSafe: "La Seguridad"}, {_id: "2", nameSafe: "Mappfre"}]
console .log (
enhanceAll (dataSafe) (dataMedical)
)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
Note that this barely uses Ramda, using only the map function. I would never introduce Ramda just for that, but if I was already using Ramda, this is nicer than this native version, which requires extra ceremony because the additional parameters supplied to Array.prototype.map (index and array) interfere with the defaulted parameters in enhance:
const enhanceAll = (safe) => (meds) => meds .map ( med => enhance (safe) (med))
Update
With the changes made to the question, the search term has to change from safeId to seguroAfiliado, making the code look like
const enhance = (safe) => (
med,
{_id, ...rest} = safe .find (({_id}) => _id == med.seguroAfiliado) || {}
) => ({...med, ...rest})
const enhanceAll = (safe) => R.map (enhance (safe))
You can see this running in Ramda's REPL.
Update 2
I tried this in node, and it worked fine:
index.js:
const R = require('ramda');
const dataMedical = [
{
_id: '5da619b36aae5e7028fc27db',
paciente: '5de31abf4c430918a39a7490',
seguroAfiliado: '5d65da2f008b72055d17abfb',
fecha: '2019-10-01T03:00:00.000Z',
motivoConsulta: 'dww',
__v: 0
}
]
const dataSafe = [ {
_id: '5d65da2f008b72055d17abfb',
nombre: 'La Seguridad',
email: 'info#laseguridad.com.ve',
numeroPoliza: '123456',
pais: 'fdsaafsd',
baremo: 'afdafds',
actoQuirurgico: 'fsdasafd',
__v: 0
}, {
_id: '5d62c609e7179a084ef359fd',
nombre: 'Mappfre',
email: 'info#mappfre.com',
numeroPoliza: '098765',
actoQuirurgico: 'acto2',
baremo: 'rweq',
pais: 'usa'
}
]
const enhance = (safe) => (
med,
{_id, ...rest} = safe .find (({_id}) => _id == med.seguroAfiliado) || {}
) => ({...med, ...rest})
const enhanceAll = (safe) => R.map (enhance (safe))
console .log (
JSON.stringify(
enhanceAll (dataSafe) (dataMedical),
null,
4
)
)
> npm install ramda
[...]
> node --version
v10.15.0
> node index
[
{
"_id": "5da619b36aae5e7028fc27db",
"paciente": "5de31abf4c430918a39a7490",
"seguroAfiliado": "5d65da2f008b72055d17abfb",
"fecha": "2019-10-01T03:00:00.000Z",
"motivoConsulta": "dww",
"__v": 0,
"nombre": "La Seguridad",
"email": "info#laseguridad.com.ve",
"numeroPoliza": "123456",
"pais": "fdsaafsd",
"baremo": "afdafds",
"actoQuirurgico": "fsdasafd"
}
]

Related

How to filter array of objects with nested objects with specific properties?

I am trying to filter a Javascript array of objects with nested objects with specific properties. I can filter the name, slug, website, launch year without any issues. But, I can not filter the category name (category.name) which is an object within the object. Why is filtering the category name not working?
var search = "qui"; // does not work (category.name)
// var search = "Sauer"; // works (name)
var data = [{ "name": "Sauer-Metz", "slug": "ab-laborum",
"website": "https://test.com", "launch_year": 2017, "category_id": 6,
"category": { "id": 6, "name": "qui", "slug": "qui" } } ];
var results = data.filter(company => [
'name', 'launch_year', 'website', 'category.name'
].some(key => String(company[key]).toLowerCase().includes(search.toLowerCase())));
console.log(results);
One way you can go about it is to have a value extractor like the one getKey below
const getKey = (value, key) => {
return key.split('.').reduce((acc, curr) => value[curr], '');
}
var results = data.filter(company => [
'name', 'launch_year', 'website', 'category.name'
].some(key => String(getKey(company, key)).toLowerCase().includes(search.toLowerCase())));
I believe you have to do a separate condition for this specific nested property, although there might be a cleaner way I don't see right now:
var results = data.filter(
(company) =>
["name", "launch_year", "website"].some((key) =>
String(company[key]).toLowerCase().includes(search.toLowerCase())
) ||
String(company["category"]["name"])
.toLowerCase()
.includes(search.toLowerCase())
);
Dot notation doesn't work like that.
const testCase1 = 'qui';
const testCase2 = 'Sauer';
const data = [
{
name: 'Sauer-Metz',
slug: 'ab-laborum',
website: 'https://test.com',
launch_year: 2017,
category_id: 6,
category: { id: 6, name: 'qui', slug: 'qui' },
},
];
const searchResults = (data, search) => {
return data.filter((item) => {
return (
item?.category?.name.toLowerCase().includes(search.toLowerCase()) ||
['name', 'launch_year', 'website'].some((key) => `${item[key]}`.toLowerCase().includes(search.toLowerCase()))
);
});
};
console.log('**CASE 1**')
console.log(searchResults(data, testCase1));
console.log('**CASE 2**')
console.log(searchResults(data, testCase2));
To use your approach you can convert 'category.name' to ['category','name'] and then use String(company[key[0]][key[1]])... whenever key is an array.
const search = "qui"; // does not work (category.name)
//const search = "Sauer"; // works (name)
const data = [{ "name": "Sauer-Metz", "slug": "ab-laborum", "website": "https://test.com", "launch_year": 2017, "category_id": 6, "category": { "id": 6, "name": "qui", "slug": "qui" } } ];
const results = data.filter(
company => [
'name', 'launch_year', 'website', ['category','name']
].some(
key =>
Array.isArray(key) ?
String(company[key[0]][key[1]]).toLowerCase().includes(search.toLowerCase()) :
String(company[key]).toLowerCase().includes(search.toLowerCase())
)
);
console.log(results);

How to remove object element that match from an array using splice?

here is my data of array1 :
[ { members: [ '60ee9148104cc81bec3b97ab' ] } ]
and here is array2:
[{"_id": "60ee9148104cc81bec3b97ab","username": "user1", "email": "user1#gmail.com"}, {"_id": "60ee917f767bd11d687326c7","username": "user2","email": "user2#gmail.com"}]
and I want to remove the object from my array2 which _id is equal to 60ee9148104cc81bec3b97ab
I have tried so far as
let user = await User.find({ _id: { $ne: req.user._id } })
const getNonfriends = (one) => {
user.splice(user.indexOf(one.members[0]), 1)
//user.filter(entry => entry._id !== one.members[0])
}
array1.map(getNonfriends)
filter or splice non of them bring my solutions.
The mistake you make is that you have similar objects, yet you search for identical objects.
var array1 = [ { members: [ '60ee9148104cc81bec3b97ab' ] } ];
var array2 = [{"_id": "60ee9148104cc81bec3b97ab","username": "user1", "email": "user1#gmail.com"}, {"_id": "60ee917f767bd11d687326c7","username": "user2","email": "user2#gmail.com"}]
for (var x of array1) {
for (var member of x.members) {
var objects = array2.filter(item => item._id === member)
for (var obj of objects) array2.splice(array2.indexOf(obj), 1)
}
}
We can use the Array.prototype.filter()
I think there is no need to find the index of the array and slice.
Also, we can use the Array.prototype.map, it is similar to use the filter function
const obj1 = [{
members: ['60ee9148104cc81bec3b97ab']
}]
const obj2 = [{
"_id": "60ee9148104cc81bec3b97ab",
"username": "user1",
"email": "user1#gmail.com"
}, {
"_id": "60ee917f767bd11d687326c7",
"username": "user2",
"email": "user2#gmail.com"
}]
const getAnswer = (obj2) => {
const res = obj2.filter(item => !obj1[0].members.includes(item._id))
return res;
}
console.log(getAnswer(obj2));
As you are working with IDs, I am going to assume that the second array cannot contain two items with the same ID.
If that assumption is correct, you could do:
const data = [{
"_id": "60ee9148104cc81bec3b97ab",
"username": "user1",
"email": "user1#gmail.com"
}, {
"_id": "60ee917f767bd11d687326c7",
"username": "user2",
"email": "user2#gmail.com"
}];
const filter = [{
members: ['60ee9148104cc81bec3b97ab']
}];
// SOLUTION 1: using Array.prototype.findIndex() and Array.prototype.splice()
const filteredDataA = [...data] // as splice() modifies the original array, I think it is safer to work on a copy of the original data
filter[0].members.forEach(id => {
const index = filteredDataA.findIndex(item => item._id === id); // find the index of the item with the same ID
if (index > -1) filteredDataA.splice(index, 1); // (if found) remove the item
})
console.log('SOLUTION 1: using Array.prototype.findIndex() and Array.prototype.splice()');
console.log(filteredDataA);
console.log('--------------------');
// SOLUTION 2: using array.prototype.filter() and array.prototype.includes()
const filteredDataB = data.filter(item => !filter[0].members.includes(item._id));
console.log('SOLUTION 2: using array.prototype.filter() and array.prototype.includes()');
console.log(filteredDataB);
console.log('--------------------');
I'd prefer "Solution 2" as I think is more readable
From the answers, I got the clue and this brings my desire results. here is one thing that array1 can have multiple elements so it needs to be mapped over with invoking the getNonfriends finction.
so,
let user = await User.find({ _id: { $ne: req.user._id } })
const getNonfriends = (one) => {
user = user.filter(item => !one.members.includes(item._id))
return user;
}
await array1.map(getNonfriends)

Using indexOf in order to filt an array - ( Next.js app with typescript )

I have this array in my next.js app
arr1
[
{
identifier: "60a17722225f2918c445fd19",
name: "Ben Awad",
_id: "60c94480b8d43c28d0a6eb73
},
{
identifier: "60a455d11fa62a1510b408f8",
name: "dev ed"
_id: "60bf62cede309f1a30fe88ab"
}
]
And i have this another big array
arr2
[
{
name: "Ben Awad",
_id: "60a17722225f2918c445fd19
},
{
name: "dev ed",
_id: "60a455d11fa62a1510b408f8"
},
{
name: "Katlyn",
_id: "60a52500ce96f30c14fdaff9"
},
{
name: "Mike",
_id: "60c95deeb8d43c28d0a6eb74"
},
{
name: "Kassandra",
_id: "60c960ddb8d43c28d0a6eb7a"
}
]
I want a new array who should have all users except for those who have similar ids with arr1
So this is the logic i did (Notice that arr1 and arr2 will change constantly)
Me = arr1
AllUsers = arr2
const LookFriends =
Me &&
AllUsers.filter(({ _id }) => {
return Me.friends.indexOf(_id) === -1;
});
console.log(LookFriends);
The output should be Katlyn, Mike and Kassandra, but the console.log says...
[
{
name: "Ben Awad",
_id: "60a17722225f2918c445fd19
},
{
name: "dev ed",
_id: "60a455d11fa62a1510b408f8"
},
{
name: "Katlyn",
_id: "60a52500ce96f30c14fdaff9"
},
{
name: "Mike",
_id: "60c95deeb8d43c28d0a6eb74"
},
{
name: "Kassandra",
_id: "60c960ddb8d43c28d0a6eb7a"
}
]
I'm really having a hard time trying to filter an array based on another array, what can i do ?
You need to use 'findIndex' in this case, then compare the _id field itself:
const LookFriends =
Me &&
AllUsers.filter(({ _id }) => {
return Me.friends.findIndex(friend => friend._id === _id) === -1;
});
If you use "indexOf", it will compare the entire object to just that _id value.
You can extract the identifiers from the first array and filter the second array if the element doesn't match any id in our object or our Set
// with an object
const ids = {}
arr1.forEach(user => {
ids[user.identifier] = true
})
const filtered = arr2.filter(user => !ids[user._id])
// or with a Set
const ids = new Set(arr1.map(user => user.identifier))
const filtered = arr2.filter(user => !ids.has(user._id))
Please have a try with this code.
Me &&
AllUsers.filter(({ _id }) => {
let bExist = false
Me.friends.map( (friend) => {
if ( friend._id === _id )
bExist = true
})
return bExist
});
Let me know if it works or not.

How can we compare two array of objects and display items from both array

I have two arrays like
const arr1=[{id:0,name:'aa',
userId:'22,23'},
{id:1,name:'bb',userId:'23'}]
const arr2=
[{id:22,username:'Peter'},
{id:23,username:'John'}]
arr1.map((val,k)=><div>
<p>val.userId</p>
</div>
I have getting output as
22,23
23
How to get an output like
Peter,John
John
You can use find() to get the username from arr2
const arr1 = [
{ id: 0, name: "aa", userId: "22,23" },
{ id: 1, name: "bb", userId: "23" },
];
const arr2 = [
{ id: 22, username: "Peter" },
{ id: 23, username: "John" },
];
const output = arr1.map(o =>
o.userId
.split(",")
.map(x => arr2.find(k => k.id === Number(x)).username)
.join(",")
);
output.map((val)=> <div><p>val</p></div>);
{arr1.map((val, k) => {
const ids = val.userId.split(",");
return ids.map((id) => {
const user = arr2.find((user) => user.id === Number(id));
return (
<div key={`${val.id}-${user.id}`}>
<p>{user.username}</p>
</div>
);
});
})}
Working Sandbox
You could with Array#reduce and Array#map
Array#reduce convert the array to object for easy to find. its better then using find with in map
Then Array#map update the new key of users.it will carry the username
const arr1=[{id:0,name:'aa', userId:'22,23'},{id:1,name:'bb',userId:'23'}]
const arr2= [{id:22,username:'Peter'}, {id:23,username:'John'}]
const obj = arr2.reduce((acc,{id,username})=>(acc[id]=username,acc),{})
const res = arr1.map(({userId,...a})=>{
const users = userId.split(',').map(id=> obj[id]).join(',')
return ({...a,userId,users})
})
console.log(res)
res.map((val,k)=><div>
<p>val.users</p>
</div>)

How to turn this ID-based objects into an array of objects?

I have data like this:
{
"-L8BpxbS70KYrZMQUF0W": {
"createdAt": "2018-03-22T16:33:57+08:00",
"email": "ss#ss.ss",
"name": "ss"
},
"-KYrZMQUF0WL8BpxbS70": {
// etc.
}
}
Which I want to turn into this:
[{
id: '-L8BpxbS70KYrZMQUF0W
createdAt: "2018-03-22T16:33:57+08:00",
email: "ss#ss.ss",
name: "ss"
}, {
id: -KYrZMQUF0WL8BpxbS70"
// etc.
}]
I'm started with this:
Object.keys(idBasedObjects).forEach(key => {
console.log(resp[key])
})
But I get undefined.
What's best way of creating this array?
Get the keys and values using Object.entries(), and Array.map() them to to the required form using object spread:
const obj = {"-L8BpxbS70KYrZMQUF0W":{"createdAt":"2018-03-22T16:33:57+08:00","email":"ss#ss.ss","name":"ss"},"-KYrZMQUF0WL8BpxbS70":{}};
const result = Object.entries(obj).map(([id, props]) => ({
id,
...props
}));
console.log(result);
Use Object.keys, Object.assign and map
var output = Object.keys(obj).map( s => Object.assign( obj[s], {id : s} ))
Demo
var obj = {
"-L8BpxbS70KYrZMQUF0W": {
"createdAt": "2018-03-22T16:33:57+08:00",
"email": "ss#ss.ss",
"name": "ss"
},
"-KYrZMQUF0WL8BpxbS70": {
"createdAt": "2018-03-22T16:33:57+08:00",
"email": "s2s#ss.ss",
"name": "ss2"
}
};
var output = Object.keys(obj).map(s => Object.assign(obj[s], {
id: s
}));
console.log(output);

Categories

Resources