How to remap array in React [duplicate] - javascript

This question already has answers here:
How to rename properties of objects in array in javascript?
(5 answers)
Closed 4 months ago.
How to do a remapo for new objects like:
...
const inputArr = [
{id: '1', name: "test1", routeName: "somethig/something"},
{id: '2', name: "something2", routeName: "foo/bar"},
{id: '3', name: "someanothrelement", routeName: "test/test"}
]
//to =>
const resultStructureArr = [
{ id: '1', value: 'somethig/something', label: 'test1' },
{ id: '2', value: 'foo/bar', label: 'something2' },
{ id: '3', value: 'test/test', label: 'someanothrelement' },
];
...
Here is the jsfiddle

Just using map() can do it
const inputArr = [
{id: '1', name: "test1", routeName: "somethig/something"},
{id: '2', name: "something2", routeName: "foo/bar"},
{id: '3', name: "someanothrelement", routeName: "test/test"}
]
let result = inputArr.map(a => ({'id':a.id,'label':a.name,'value':a.routeName}))
console.log(result)

We can use traditional for loop for this. Where we may loop to the length of list and for each iteration we may add new object into result array using Array.prototype.push method. Secondly we are doing the same thing with foreach loop. Third I'm using Array.prototype.map method, Which creates a new result for each iteration, in our case we are returning our new object. Lastly we are using Array.prototype.reduce method, with this method we can initialize a starting value which in my case I'm using empty array, then for each iteration I'm pushing a new object in that array and returning it.
const inputArr = [
{ id: "1", name: "test1", routeName: "somethig/something" },
{ id: "2", name: "something2", routeName: "foo/bar" },
{ id: "3", name: "someanothrelement", routeName: "test/test" },
];
// Using for loop
let result = [];
for (let i = 0; i < inputArr.length; i++) {
result.push({
id: inputArr[i].id,
value: inputArr[i].routeName,
label: inputArr[i].name,
});
}
console.log(result);
result = [];
// using foreach loop
inputArr.forEach((item) => {
result.push({ id: item.id, label: item.name, value: item.routeName });
});
console.log(result);
result = [];
// using map
result = inputArr.map((item) => ({
id: item.id,
label: item.name,
value: item.routeName,
}));
console.log(result);
result = [];
// using reduce
result = inputArr.reduce((acc, curr) => {
acc.push({ id: curr.id, label: curr.name, value: curr.routeName });
return acc;
}, []);
console.log(result);

Related

Looping through inner array in a filter function in JS

I'm trying to filter the array here but the result seem to be empty. How do I loop through inner array in a filter function?
Below is the snippet
const carIds = ['100', '101'];
const carsList = [{
name: 'BMW',
id: '100'
}, {
name: 'Jeep',
id: '101'
}, {
name: 'Audi',
id: '103'
}];
const result = carsList.filter((val) => val.id === carIds.map((val) => val))
console.log('result', result)
Expected output should be
[{
name: 'BMW',
id: '100'
}, {
name: 'Jeep',
id: '101'
}]
Could anyone please advise?
I'm not completely sure what you're trying to do with the .map() method, but you're not using it right. .map() applies a transformation function to each element of the array, then returns a new array of the result. See the MDN article for help with the correct usage.
In your case, you can just use the .includes() method to check if the array includes the value. Like this:
const carIds = ['100', '101'];
const carsList = [{
name: 'BMW',
id: '100'
}, {
name: 'Jeep',
id: '101'
}, {
name: 'Audi',
id: '103'
}];
const result = carsList.filter(val => carIds.includes(val.id))
console.log('result', result)
Note that in this case, it is faster to use a Set, as it can check for membership in O(1) time rather than the O(n) that an array offers. Expand the snippet below for an example:
const carIds = new Set(['100', '101']);
const carsList = [{
name: 'BMW',
id: '100'
}, {
name: 'Jeep',
id: '101'
}, {
name: 'Audi',
id: '103'
}];
const result = carsList.filter(val => carIds.has(val.id))
console.log('result', result)
I'm guessing you want to return the cars who's ID's are included in the carIds array?
If so you want to use the .includes() method instead of .map().
const result = carsList.filter((val) => carIds.includes(val.id))

How to filter array of objects by another array of objects by property using javascript

I have two nested array of objects, how to compare two array of objects by
id from arrobj1 and assignId from arrobj2 using javascript
So, I would to know how to compare array of objects by id and assignId and return array of objects using javascript
Tried
const result = arrobj1.filter(arr1 => {
arrobj2.find(arr2 => arr2.assignId === arr1.id)
});
var arrobj1 =[
{id: 1, name: 'xxx', value:100},
{id: 2, name: 'yyy', value:200},
{id: 3, name: 'zzz', value:400}
]
var arrobj2 =[
{country: 'IN', name: 'lina', assignId:2},
{country: 'MY', name: 'john', assignId:3},
{country: 'SG', name: 'peter', assignId:6}
]
Expected Code:
[
{id: 2, name: 'yyy', value:200},
{id: 3, name: 'zzz', value:400}
]
You have it almost correct, but you need to return in your filter, either by explicitly adding the return keyword or by removing the braces to use the arrow function's implicit return:
const result = arrobj1.filter(arr1 =>
arrobj2.find(arr2 => arr2.assignId === arr1.id)
)
// or
const result = arrobj1.filter(arr1 => {
return arrobj2.find(arr2 => arr2.assignId === arr1.id)
})
We can combine Array.filter() and Array.some() to make it more simple
let result = arrobj1.filter(a1 => arrobj2.some(a2 => a2.assignId === a1.id) )
console.log(result)
For your code,the reason is that you have missing return when invoke find
var arrobj1 =[
{id: 1, name: 'xxx', value:100},
{id: 2, name: 'yyy', value:200},
{id: 3, name: 'zzz', value:400}
]
var arrobj2 =[
{country: 'IN', name: 'lina', assignId:2},
{country: 'MY', name: 'john', assignId:3},
{country: 'SG', name: 'peter', assignId:6}
]
let result = arrobj1.filter(a1 => arrobj2.some(a2 => a2.assignId === a1.id) )
console.log(result)
You can generally go with the filter and some combination as #flyingfox mentioned in the answer, But if you'd have thousands of records then your time complexity would increase which you can solve by removing the nested some loop.
So more performant code would look like the following for a bigger data set.
And yes, Either use return with braces or simply remove the braces for one-liner returns!
var arrobj1 = [
{ id: 1, name: 'xxx', value: 100 },
{ id: 2, name: 'yyy', value: 200 },
{ id: 3, name: 'zzz', value: 400 },
]
var arrobj2 = [
{ country: 'IN', name: 'lina', assignId: 2 },
{ country: 'MY', name: 'john', assignId: 3 },
{ country: 'SG', name: 'peter', assignId: 6 },
]
var obj = {}
for (const elem of arrobj2) {
obj[elem.assignId] = true
}
let result = arrobj1.filter((a1) => obj[a1.id])
console.log(result)

Remove equal objects from array

I have the following problem in JavaScript: I want to check an array for duplicates. My example array only has 6 objects here.
var list = [
{id: "1", label: "Nils"},
{id: "2", label: "Max"},
{id: "3", label: "Thomas"},
{id: "4", label: "Tom"},
{id: "5", label: "Joschua"},
{id: "5", label: "Joschua"}];
In the later project it can also be more than 500, which I import via a CSV file.
And now I want to remove duplicates. At first I tried the set method:
var newList = [... new Set(list)];
console.log(newList);
The result is false. The array has the same objects.
Then I tried a simple if query:
if(list[4]==list[5]){
console.log("equal") }else{
console.log("unequal")}
The result is unequal. I don't understand why.
The array should look like this:
[{ id: '1', label: 'Nils' },
{ id: '2', label: 'Max' },
{ id: '3', label: 'Thomas' },
{ id: '4', label: 'Tom' },
{ id: '5', label: 'Joschua' }]
If the ids are meant to be unique, you can use Array#filter with a Set based on the id.
var list = [
{id: "1", label: "Nils"},
{id: "2", label: "Max"},
{id: "3", label: "Thomas"},
{id: "4", label: "Tom"},
{id: "5", label: "Joschua"},
{id: "5", label: "Joschua"}];
const set = new Set,
res = list.filter(x => !set.has(x.id) && set.add(x.id));
console.log(res);
Set cannot compare object altogether, it only works with primitives types like number or string.
You can use a Map that is based on a key/value paradigm though, like :
const list = [
{id: '1',label: 'Nils'},
{id: '2', label: 'Max'},
{id: '3', label: 'Thomas'},
{id: '4', label: 'Tom'},
{id: '5', label: 'Joschua'},
{id: '5', label: 'Joschua'},
];
const map = new Map();
// Push the values into the map
list.forEach(({
id,
label,
}) => map.set(id, label));
// Transform the map into an array of object
const uniqueList = Array.from(map, ([id, label]) => ({
id,
label,
}));
console.log(uniqueList);
Or using an Array.reduce combined with an Array.map
const list = [
{id: '1', label: 'Nils'},
{id: '2', label: 'Max'},
{id: '3', label: 'Thomas'},
{id: '4', label: 'Tom'},
{id: '5', label: 'Joschua'},
{id: '5', label: 'Joschua'},
];
const uniqueList = Object.entries(list.reduce((tmp, {
id,
label,
}) => {
tmp[id] = label;
return tmp;
}, {})).map(([
id,
label,
]) => ({
id,
label,
}));
console.log(uniqueList);
Then I tried a simple if query:
if(list[4]==list[5]){ console.log("equal") }else{
console.log("unequal")} The result is unequal. I don't understand why.
== uses Abstract Equality Comparison Algorithm.
At first this algorithm checks if the types are the same
-> which they are.
Then the algorithm proceeds with the first step, and goes down to check if they both referencing the same object
-> they don't referencing the same object
That is the reason why it prints out false
Each usage of {} creates a new object, so this check fails and the result is false.
let a = {}
let b = {}
console.log(a==b);
Or like in your example
let a = {id: "5", label: "Joschua"};
let b = {id: "5", label: "Joschua"};
console.log(a==b);
Solution
To check if two objects are equal you can do the following
let a = {
id: 5,
name: "Max"
}
let b = {
id: 5,
name: "Max"
}
function areTheObjectsEqual(obj1, obj2) {
let keysObj1 = Object.keys(obj1);
let keysObj2 = Object.keys(obj2);
// first check if they have the same amount of keys, if not return false
if (keysObj1.length !== keysObj2.length) {
return false;
}
let valuesObj1 = Object.values(obj1);
let valuesObj2 = Object.values(obj2);
// then compare if they have the same values
for(let i = 0; i < valuesObj1.length; i++){
if(valuesObj1[i] !== valuesObj2[i]){
return false;
}
}
return true;
}
console.log(areTheObjectsEqual(a,b));

Why async.map returns multiple copies of array?

const async = require('async');
const arr = [
{ name: 'john', id: '1' },
{ name: 'Andrie', id: '2' }]
let collectArr = [];
let data = async.mapLimit(arr, 5, async function (input) {
collectArr.push({ name: input.name, id: input.id });
return collectArr;
})
data.then((result) =>{
console.log('success',result);
}).catch(e => console.log('err'));
So here i am providing array to async.mapLimit without callback and expecting promise here.
Expected Output :- [ { name: 'john', id: '1' }, { name: 'Andrie', id: '2' } ] ,
Got Result :-
[ [ { name: 'john', id: '1' }, { name: 'Andrie', id: '2' } ],
[ { name: 'john', id: '1' }, { name: 'Andrie', id: '2' } ] ]
So my question is why it is creating multiple copies of array, how to deal with this?
You are needlessly returning a sub array, and the same array reference each iteration, when all you want is to return the new object.
let data = async.mapLimit(arr, 5, async function (input) {
return { name: input.name, id: input.id };
});
Not sure why you need this to be async

Remove duplicates from array of objects - Javascript [duplicate]

This question already has answers here:
How to remove all duplicates from an array of objects?
(77 answers)
Closed 2 years ago.
Hi I'm trying to remove duplicates from array of objects. But that is not working as expected.
This is my array:
const arr = [{
PData: [{
id: '1',
name: 'Book'
},
{
id: '2',
name: 'Bag'
},
{
id: '2',
name: 'Bag'
},
]
}]
const RemoveDuplicates = (array, key) => {
return array.reduce((arr, item) => {
const removed = arr.filter(i => i[key] !== item[key]);
return [...removed, item];
}, []);
};
var result = RemoveDuplicates(arr, 'id')
console.log(result);
Expected output:
[{
PData: [{
id: '1',
name: 'Book'
},
{
id: '2',
name: 'Bag'
},
]
}]
Based on id it supposed to remove duplicates but this is not happening currently..I know that couple of questions are existed regarding this but nothing is working for me. So anyone plz suggest me how to do.
You can use filter here is how on id and name.
const arr = [{
PData: [{
id: '1',
name: 'Book'
},
{
id: '2',
name: 'Bag'
},
{
id: '2',
name: 'Bag'
},
]
}]
arr[0].PData = Object.values(arr[0].PData).filter((v,i,a)=>a.findIndex(t=>(t.id === v.id && t.name=== v.name))===i)
console.log(arr[0].PData);

Categories

Resources