1

I am new to the react, Here I am trying to get the unique elements from the newly created array of object.

const data = _.uniq(
  orderData?.Sessions.map(session => ({
    label: `${session.Activity.Name}`,
    value: `${session.Activity.Name}`
  }))
);

I have tried this but, still, it returns me the array of the object which has the unique elements using any of the two keys.

an object should not be duplicated.

can anyone help me with this?

2 Answers 2

2

It should be _.uniqBy(), refer uniqBy

const data = _.uniqBy(
  orderData ? .Sessions.map(session => ({
    label: `${session.Activity.Name}`,
    value: `${session.Activity.Name}`
  })), 'label' or 'value'
);

It should be either by label or by value

Example

document.querySelector("body").onload = function() {
  // By 'label'
  console.log("By label");
  console.log(
    _.uniqBy(
      [
        {'label' : 'name', 'value' : 'Test Name 1'},
        {'label' : 'name', 'value' : 'Test Name 2'},
        {'label' : 'company', 'value' : 'Test Company 1'}
      ], 'label'
    )
  )
  // By 'vlaue'
  console.log("By value");
  console.log(
    _.uniqBy(
      [
        {'label' : 'name', 'value' : 'SO User'},
        {'label' : 'name', 'value' : 'SO User'},
        {'label' : 'company', 'value' : 'Test Company 1'}
      ], 'value'
    )
  )
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

0

You have to use _.uniqBy(data, 'id');//id that is key you have to remove duplicate value from array

Your Scenario will be used like this

if removed by a label then

const data = _.uniqBy(
  orderData ? .Sessions.map(session => ({
    label: `${session.Activity.Name}`,
    value: `${session.Activity.Name}`
  })),'label'
);

if removed by a value then

const data = _.uniqBy(
  orderData ? .Sessions.map(session => ({
    label: `${session.Activity.Name}`,
    value: `${session.Activity.Name}`
  })),'value'
); 

If you get more details then Link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.