Remove duplicates from array of objects - Javascript [duplicate] - javascript

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);

Related

How to remap array in React [duplicate]

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);

Create a new array on a combination of arrays based on a key in the arrays javascript [duplicate]

This question already has answers here:
Merge two array of objects based on a key
(23 answers)
Closed 1 year ago.
I have two arrays as input (array1 & array2) for which I want to check if there is a match on id.
If there is a match they should be included in a new array called result.
array1 = [
{ x_id:6711230070958, id:279482 },
{ x_id:6770878283950, id:213 },
{ x_id:6753301168302, id:330120 }
];
array2 = [
{ id: 279482, stock: 9 },
{ id: 31231, stock: 2 },
{ id: 330120, stock: 2 }
];
result [
{ x_id:6711230070958, id: 279482, stock: 9 },
{ x_id:6753301168302, id: 330120, stock: 2 }
]
For finding the matches I tried using a filter with includes.
Anybody some thoughts on this?
Try this
array1 = [
{ x_id:6711230070958, id:279482 },
{ x_id:6770878283950, id:213 },
{ x_id:6753301168302, id:330120 }
];
array2 = [
{ id: 279482, stock: 9 },
{ id: 31231, stock: 2 },
{ id: 330120, stock: 2 }
];
let arr3 = array1.map((item, i) => Object.assign({}, item, array2[i]));
console.log(arr3)
Try this:
array1 = [
{ x_id:6711230070958, id:279482 },
{ x_id:6770878283950, id:213 },
{ x_id:6753301168302, id:330120 }
];
array2 = [
{ id: 279482, stock: 9 },
{ id: 31231, stock: 2 },
{ id: 330120, stock: 2 }
];
result = [];
array1.forEach(ele=> {
let match = array2.find(e => e.id == ele.id);
if(match)
result.push(Object.assign({}, ele, match))
})

How to compare data in two arrays and return the unmatched array in javascript? [duplicate]

This question already has answers here:
Compare two Arrays with Objects and create new array with unmatched objects
(2 answers)
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 2 years ago.
Here is my problem statement.
I have two arrays
assignedArr = [{ id: 'abc1' }, { id: 'abc2' }, { id: 'abc3' }];
unAssignedArr = [{ id: 'abc1' }, { id: 'abc2' }, { id: 'abc3'}, { id: 'abc4' }];
I have to compare assingedArr with unAssignedArr, and return the unmatched array item.
For example, In the above example,
the result should be
newArr = [{ id: 'abc4' }];
Like soo...
Any suggestions would greatly appriaciated
You could use array Array.prototype.filter with Array.prototype.some method to get your result.
const assignedArr = [{ id: 'abc1' }, { id: 'abc2' }, { id: 'abc3' }];
const unAssignedArr = [
{ id: 'abc1' },
{ id: 'abc2' },
{ id: 'abc3' },
{ id: 'abc4' },
];
const ret = [
...unAssignedArr.filter((x) => !assignedArr.some((y) => x.id === y.id)),
...assignedArr.filter((x) => !unAssignedArr.some((y) => x.id === y.id)),
];
console.log(ret);

How to find an object from recursive array of objects that is matching with the id using javascript and react?

i have data like below,
const items = [
{
id: '1',
name: 'item1',
subItems: [{
id: '1',
name: 'subitem-1',
}],
},
{
id: '2',
name: 'item2',
subItems: [{
id: '2',
name: 'subitem-1',
}],
}
]
Now i want to find the subItem that matches with id 2. so from above data expected output is
{
id: '2',
name: 'subitem-1',
}
i have tried something like below,
const subItem = Items.find(
(item: any) =>
item.subItems &&
item.subItems.some(
(subItem: any) => subItem.id === '2'
)
);
but this will return the item that contains the subItem with id = '2'.
how can i fix the above code such that i get the SubItem instead of item?
could someone help me with this. thanks.
You could use the following, which will search and return only the inner object that is found.
const items = [
{
id: "1",
name: "item1",
subItems: [
{
id: "1",
name: "subitem-1"
}
]
},
{
id: "2",
name: "item2",
subItems: [
{
id: "2",
name: "subitem-1"
}
]
}
];
function innerFind(array, key, value) {
for (const obj of array) {
const item = obj.subItems.find((el) => el[key] === value);
if (item != null) return item;
}
}
console.log(innerFind(items, 'id', '2'));
You pass in your items array, the key you want to search for ('id'), and then the value you want to search for ('2'). This function will return the first sub item it finds that matches.

Filtering array of objects if specific key contains search term

I am trying to filter through an object with multiple key/value pairs by a specific key. It appears that the code I've written is searching the entire object regardless of the key...
If key name contains the search term, return the search term.
Array of Objects:
export const someArrayOfObjects = [
{ id: '1', name: 'Something' },
{ id: '2', name: 'Another' },
{ id: '3', name: 'Lets do one more' },
]
Search:
const searchResults = someArrayOfObjects.filter((o) =>
Object.keys(o).some((k) => o[k].toString().toLowerCase().includes(searchTerm.toLowerCase()))
);
So if I search "Something", I only want it to loop through name to search for that term...
You don't need the Object.keys loop.
const someArrayOfObjects = [
{ id: '1', name: 'Something' },
{ id: '2', name: 'Another' },
{ id: '3', name: 'Lets do one more' },
];
let key = 'name';
let searchTerm = 'th';
const res = someArrayOfObjects.filter(o =>
o[key].toLowerCase().includes(searchTerm.toLowerCase()));
console.log(res);
similar to iota's, you don't need to create the extra array with Object.keys.
just loop/check every item inside the original array with the 'name' key.
you can also try to make it more reusable like below.
const someArrayOfObjects = [
{ id: '1', name: 'Something' },
{ id: '2', name: 'Another' },
{ id: '3', name: 'Lets do one more' },
];
const search = function (anyArray, searchTerm) {
return anyArray.filter((obj) => {
if (obj.name === searchTerm) {
return obj.name;
}
return false;
});
};
const case1 = search(someArrayOfObjects, 'Something');
console.log(case1);

Categories

Resources