How to merging two lists in React? - reactjs

I need help with merging 2 lists in ReactJs.
for example,
list one :
[
{id:1,name:"abc",city:"ddd"},
{id:2,name:"cde",city:"ddd"},
{id:3,name:"ttt",city:"fff"}
]
list two:
[
{id:1,name:"abc"},
{id:3,name:"ttt"}
]
and the result that I want to get is
[
{id:1,name:"abc",city:"ddd"},
{id:3,name:"ttt",city:"fff"}
]
What is the best clearly way to do that?

You can use filter and some array method.
const arr1 = [
{id:1,name:"abc",city:"ddd"},
{id:2,name:"cde",city:"ddd"},
{id:3,name:"ttt",city:"fff"}
];
const arr2 = [
{id:1,name:"abc"},
{id:3,name:"ttt"}
];
const filteredArray = arr1.filter((el) => {
return arr2.some((x) => {
return x.id === el.id && x.name === el.name;
});
});
console.log(filteredArray);

Related

How to return the index from two array?

I have two array my desired result is to return the index from matching values. How to do that?
For instance I have these two array:
const arr1 = [ monkey, lion, giraffe, bear, ant, fish, dinosaur ]
cosnt arr2 = [ lion, giraffe, bear ]
How to return the result as the index from matching values?
You can try like this.
const arr1 = [ 'monkey', 'lion', 'giraffe', 'bear', 'ant', 'fish', 'dinosaur' ]
const arr2 = [ 'lion', 'giraffe', 'bear' ];
let index = [];
arr2.forEach(function(a,i){
index.push(arr1.indexOf(a));
});
console.log(index);
//another way using map function
let result = arr2.map((a,i)=>{
return arr1.indexOf(a);
})
console.log(result);

How can I use .map on an array to create a new JSON object for each item?

how can I use map on an array to map each item to a new JSON structure?
For example my original array looks like this:
result= [
{
"pageIndex":1,
"pageName":"home",
"cssConfiguration":"fa fa-home"
}, ...]
And I want to use .map to create a different structure for the JSON objects, for example:
modifiedResult = [
{
"id":1,
"name":"Home"
},...]
I've tried to do something like this:
result.map((resultItem) => { name: resultItem["pageName"], id:resultItem["pageIndex"]});
But it doesn't work :(
In your approach are missing the parentheses within the handler:
result.map((resultItem) => { name: resultItem["pageName"], id:resultItem["pageIndex"]});
^
You can use the function map and destructuring-assignment as follow:
let arr = [ { "pageIndex":1, "pageName":"home", "cssConfiguration":"fa fa-home" }],
result = arr.map(({pageIndex: id, pageName: name}) => ({id, name}));
console.log(result)
You can use map:
const result = arr.map(({pageIndex, pageName}) => ({id: pageIndex, name: pageName}))
An example:
let arr = [
{
"pageIndex":1,
"pageName":"home",
"cssConfiguration":"fa fa-home"
}]
const result = arr.map(({pageIndex, pageName}) => ({id: pageIndex, name: pageName}))
console.log(result)

How to merge Array Observavble of array in only one Observable of array with RXJS?

I want execute x requests in paralel and merge array Observavble of array in only one Observable of array with RXJS?
public getMetrics(url: string): Observable<GenericMetric[]> {
const ox: Observable<GenericMetric[]>[] = [];
res.forEach(elem => {
ox.push(this.http.get<GenericMetric[]>(url));
});
return forkJoin(...ox);
}
I try:
return forkJoin(...ox); // return array of GenericMetric[] but I want all results in GenericMetric[]
I looking for how to merge my array of array result in olny one array
return forkJoin(ox).pipe(?????);
EDIT:
I try:
return forkJoin(...ox).pipe(tap(d => console.log(d) ));
and my result is:
[
[{a:1}, {a:2}, {a:3}],
[{a:4}, {a:5}]
]
but I want :
[{a:1}, {a:2}, {a:3}, {a:4}, {a:5}]
This is a demo on how you can achieve the desired results. You can use ES6's spread syntax to flatten to array of arrays.
const arr = [
[{a:1}, {a:2}, {a:3}],
[{a:4}, {a:5}]
];
const res = [];
arr.map(item => {
res.push(...item)
})
console.log(res)
forkJoin(ox) will return you an observable of type Observable<GenericMetric[]>[], which means it is an array of GenericMetric[]. There is no way you can simplify that into an array of GenericMetric (GenericMetric[]).
However, you can still manipulate the result of forkJoin(ox) by making use of pipeable operators such as map,
forkJoin(ox)
.pipe(
map(res => {
const result = [];
res.map(elem => {
res.push(...elem)
});
return result;
}),
).subscribe(res => {
console.log(res);
// do the rest
})
My result is a unic element tab of tab, but if you have multiple tab of tab
[
[
[{a:1}, {a:2}, {a:3}],
[{a:4}, {a:5}]
],
[
[{a:6}, {a:7}, {a:8}],
[{a:9}, {a:10}]
]
]
, you can use switchMap.
public getMetrics(url: string): Observable<GenericMetric[]> {
const ox: Observable<GenericMetric[]>[] = [];
res.forEach(elem => {
ox.push(this.http.get<GenericMetric[]>(url));
});
return forkJoin(ox).pipe(switchMap(allGenericMetrics => {
let genericMetrics: GenericMetric[] = [];
allGenericMetrics.forEach(metrics => {
genericMetrics = genericMetrics.concat(metrics);
});
return of(genericMetrics);
})
);
}

Searching for data in arrays [Node.JS]

I have a question:
(sorry for the bad formatting)
I have an array:
[
{
"data": [
[
"kek",
"lol"
],
[
"notkek",
"notlol"
]
]
}
]
If someone writes "kek" it should search it in the "data" array and return the "kek" position inside its array
(["kek","lol"])
and its array position
{
"data": [
[
"kek",
"lol"
]}
(in this case "data[0]")
If anybody knows the answer, please help me
The method Array.findIndex and Array.includes may help you
const obj = {
data: [
[
'kek',
'lol'
],
[
'notkek',
'notlol'
],
],
};
const keyToSearch = 'kek';
// We look for the key
const index = obj.data.findIndex(x => x.includes(keyToSearch));
if (index === -1) {
console.log(`We didn't found ${keyToSearch}`);
} else {
console.log(`We found ${keyToSearch} at index ${index}`);
}
Double index recuperation
const obj = {
data: [
[
'kek',
'lol'
],
[
'notkek',
'notlol'
],
[
'notkek',
'notlol',
'otherstuff',
'kek',
'test',
],
],
};
const keyToSearch = 'kek';
const ret = obj.data.reduce((tmp, x, xi) => {
// We look for the key
const index = x.findIndex(y => y === keyToSearch);
if (index === -1) return tmp;
return [
...tmp,
{
absoluteIndex: xi,
relativeIndex: index,
},
];
}, []);
if (!ret.length) {
console.log(`We didn't found ${keyToSearch}`);
} else {
ret.forEach(({
absoluteIndex,
relativeIndex,
}) => console.log(
`We found ${keyToSearch} at`,
`data index ${absoluteIndex}, in ${relativeIndex} position`,
));
}
userInput = 'kek'
let item = data.map((item, indx) => {
item.includes(userInput) ? return({"indx":indx,"nestedIndex":item.indexOf(userInput)}) : null
})
map over the data array and if the nested array had the item your searching for than return the index of the array and the index of the item with in that array

ES6: Merge two arrays into an array of objects

I have two arrays that I want to merge together to one array of objects...
The first array is of dates (strings):
let metrodates = [
"2008-01",
"2008-02",
"2008-03",..ect
];
The second array is of numbers:
let figures = [
0,
0.555,
0.293,..ect
]
I want to merge them to make an object like this (so the array items match up by their similar index):
let metrodata = [
{data: 0, date: "2008-01"},
{data: 0.555, date: "2008-02"},
{data: 0.293, date: "2008-03"},..ect
];
So far I do this like so: I create an empty array and then loop through one of the first two arrays to get the index number (the first two arrays are the same length)... But is there an easier way (in ES6)?
let metrodata = [];
for(let index in metrodates){
metrodata.push({data: figures[index], date: metrodates[index]});
}
The easiest way is probably to use map and the index provided to the callback
let metrodates = [
"2008-01",
"2008-02",
"2008-03"
];
let figures = [
0,
0.555,
0.293
];
let output = metrodates.map((date,i) => ({date, data: figures[i]}));
console.log(output);
Another option is to make a generic zip function which collates your two input arrays into a single array. This is usually called a "zip" because it interlaces the inputs like teeth on a zipper.
const zip = ([x,...xs], [y,...ys]) => {
if (x === undefined || y === undefined)
return [];
else
return [[x,y], ...zip(xs, ys)];
}
let metrodates = [
"2008-01",
"2008-02",
"2008-03"
];
let figures = [
0,
0.555,
0.293
];
let output = zip(metrodates, figures).map(([date, data]) => ({date, data}));
console.log(output);
Another option is to make a generic map function which accepts more than one source array. The mapping function will receive one value from each source list. See Racket's map procedure for more examples of its use.
This answer might seem the most complicated but it is also the most versatile because it accepts any number of source array inputs.
const isEmpty = xs => xs.length === 0;
const head = ([x,...xs]) => x;
const tail = ([x,...xs]) => xs;
const map = (f, ...xxs) => {
let loop = (acc, xxs) => {
if (xxs.some(isEmpty))
return acc;
else
return loop([...acc, f(...xxs.map(head))], xxs.map(tail));
};
return loop([], xxs);
}
let metrodates = [
"2008-01",
"2008-02",
"2008-03"
];
let figures = [
0,
0.555,
0.293
];
let output = map(
(date, data) => ({date, data}),
metrodates,
figures
);
console.log(output);
If you use lodash, you can use zipWith + ES6 shorthand propery names + ES6 Arrow functions for a one-liner, otherwise see #noami's answer.
const metrodata = _.zipWith(figures, metrodates, (data, date)=> ({ data, date }));

Resources