1

I have two arrays, one which I am passing in as props called 'navPrimary' and the other which I am storing in state called 'dataArray'. What I am trying to do is loop through the navPrimary array and then grab the label and only add it to the 'dataArray' if it don't already exist. So far it works but will add it if it exists or not. I know I can use indexOf or filter to get what I need I just not know the syntax or wrapping technique to get it to work.

const [dataArray, setDataArray] = useState([]);

setDataArray(dataArray.concat(navPrimary.map((item) => item.label)));

3 Answers 3

2

If you don't want dataArray to contain duplicate elements at all Set can help:

setDataArray([...new Set(dataArray.concat(navPrimary.map((item) => item.label)))]);
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

setDataArray(dataArray.concat(navPrimary.map((item) => item.label)).filter(label => !dataArray.includes(label)));

Comments

0

I would create a separate hook to handle this generic logic and change how you store the data.

// hooks.js
export const useUniqueElements = (data) => {
  const [dataSet, updateDataSet] = useState(new Set(data));
  
  const addElements = (newData) => {
    updateDataSet(new Set([
      ...dataSet,
      ...newData
    ]));
  }

  return {
    data: [...dataSet],
    addElements
  }
}

// helpers.js

export const getLabels = (data) => data.map(({label}) => label);

// MyComponent.js
const MyComponent = (initialList) => {
  const {addElements, data} = useUniqueElements(getLabels(initialList));

  const onSubmit = (newList) => {
    addElements(getLabels(newList));
  }

  // render stuff here
}

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.