I want to build a self updating filter with checkboxes.
My Data:
const Shooting= [
{
name: "John & Johna ",
tag: ["wedding", "couple"],
img: [ src1 , src2, ...] //irrelevant
},
{
name: "Mario & Marie",
tag: ["couple", "NSFW"],
img: [ src1 , src2, ...] //irrelevant
},
];
export default Shooting;
how my output should look like that:
Filter:
[]wedding
[]couple
[]NSFW
// [] are checkboxes, "couple" is a duplicate in the array
My code idea:
- Get all tags into a new array
- Build function to remove duplicates from new array
- list the filtered array with map-function -> Obj.map((tag))=>{...}
My question:
How can I get all tags in a new list?
CodePudding user response:
You can try with [...new Set(Shooting.map(({ tag }) => tag).flat(1))]
,
-> Shooting.map(({tag}) => tag)
will give back the tags in array.
-> Then we can use array.flat() to concatenate the tags.
-> Then to remove duplicate, we use ...new Set(...)
.
const App = () => {
const Shooting = [
{
name: "John & Johna ",
tag: ["wedding", "couple"],
img: ["src1", "src2"]
},
{
name: "Mario & Marie",
tag: ["couple", "NSFW"],
img: ["src1", "src2"]
}
];
const result = [...new Set(Shooting.map(({ tag }) => tag).flat(1))];
return <div>
<h2> Filter: </h2>
<ul>
{
result.map((list, i) => <div key={i}><input type="checkbox" /> {list} </div> )
}
</ul>
</div>
}
// Render it
ReactDOM.createRoot(
document.getElementById("root")
).render(
<App />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
CodePudding user response:
Create reduce
function with set
const Shooting= [
{
name: "John & Johna ",
tag: ["wedding", "couple"],
},
{
name: "Mario & Marie",
tag: ["couple", "NSFW"],
},
];
const result = Shooting.reduce((acc, item) => {
return [ ...new Set([...acc, ...item.tag]) ]
}, [])
console.log(result)
CodePudding user response:
You can use a reducer to get all unique tags
const array = [
{
name: "name1",
tag: ["tag1", "tag2"],
},
{
name: "name2",
tag: ["tag2", "tag3"],
},
];
const tags = array.reduce((acc, item) => {
item.tag.forEach((tag) => {
if (!acc.includes(tag)) {
acc.push(tag);
}
});
return acc;
}, []);
Then with your tags you can do whatever you want. Good luck!