I am trying to remove the duplicate from the below array of Object which has some nested element with array
Below is my array.
{
field: ‘A’,
value: {
key_A: ['ajd', 'ajd', 'kajd'],
},
},
{
field: ‘A’,
value: {
key_B: ['123', '4', '45', '94'],
},
},
{
field: 'A',
value: {
key_A: ['ajd', 'ajd', ''],
},
},
{
field: ‘A’,
value: {
key_B: ['123', '4', '45'],
},
},
{
field: ‘Z’,
value: {
key_A: ['ajdm', 'askjd', 'kajd'],
},
},
{
field: ‘Z’,
value: {
key_B: ['13', '123', '1823'],
},
},
{
field: ‘Z’,
value: {
key_A: ['ajdm', 'askjd', ''],
},
},
{
field: ’Z’,
value: {
key_B: ['13', '123', ''],
},
},
];
and I want to keep the 1st key under each field i.e 1st key_A under field 'A' and 1st key_B under field 'A'
same for field 'Z'
so final o/p:
{
field: ‘A’,
value: {
key_A: ['ajd', 'ajd', 'kajd'],
},
},
{
field: ‘A’,
value: {
key_B: ['123', '4', '45', '94'],
},
},
{
field: ‘Z’,
value: {
key_A: ['ajdm', 'askjd', 'kajd'],
},
},
{
field: ‘Z’,
value: {
key_B: ['13', '123', '1823'],
},
},
];
I tried some logic with filter looping over the array but for the nested could not figure out a logic.
CodePudding user response:
A possible implementation using the answer provided here. the findIndex
gives the index of first element that satisfies the condition and the filter
therefore filters out the first elements that satisfies the condition.
Object.keys(t.value)[0]
gives either "key_A"
or "key_B"
depending on the element
let arr = [ { field: 'A', value: { key_A: ['ajd', 'ajd', 'kajd'], }, }, { field: 'A', value: { key_B: ['123', '4', '45', '94'], }, }, { field: 'A', value: { key_A: ['ajd', 'ajd', ''], }, }, { field: 'A', value: { key_B: ['123', '4', '45'], }, }, { field: 'Z', value: { key_A: ['ajdm', 'askjd', 'kajd'], }, }, { field: 'Z', value: { key_B: ['13', '123', '1823'], }, }, { field: 'Z', value: { key_A: ['ajdm', 'askjd', ''], }, }, { field:'Z', value: { key_B: ['13', '123', ''], }, }, ];
let res = arr.filter((v, i, self) =>
i === self.findIndex((t) => (
t.field === v.field && Object.keys(t.value)[0] === Object.keys(v.value)[0]
))
)
console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }