[英]Map two arrays and compare in Javascript(React)
i built a table and it has too long columns, and i was asked to create a checkbox group where a user can sort what columns he or she wanna see.我建立了一个表格,它的列太长,我被要求创建一个复选框组,用户可以在其中对他或她想要查看的列进行排序。 He can uncheck any checkbox to hide the specific column and check to show.他可以取消选中任何复选框以隐藏特定列并选中以显示。
Lets's say, this is my table column array:比方说,这是我的表列数组:
const column = [
{
key: '123',
title: 'column_a',
},
{
key: '234',
title: 'column_b',
},
{
key: '345',
title: 'column_c',
},
{
key: '567',
title: 'column_d',
}
]
I created the checkbox group in the way that it returns an array when on change, like this:我以在更改时返回数组的方式创建了复选框组,如下所示:
const selectedOnes = ["column_b", "column_c"];
And i only want the column
those match selectedOnes
我只想要那些匹配selectedOnes
的column
To find the selected columns you can use this要查找选定的列,您可以使用它
const filteredColumns = (columns, selectedColumns)=>{
return columns.filter(column => selectedColumns.includes(column.title))
}
Are you looking matched array like this你在看这样匹配的数组吗
const column = [ { key: '123', title: 'column_a', }, { key: '234', title: 'column_b', }, { key: '345', title: 'column_c', }, { key: '567', title: 'column_d', } ] const selectedOnes = ["column_b", "column_c"]; const result = column.filter(col => { return selectedOnes.find(selected=> selected === col.title) }) console.log(result);
I think you are trying to filter columns from the table dynamically.我认为您正在尝试动态过滤表中的列。
The following code will help you.下面的代码会帮助你。
import { useState } from "react";
import "./styles.css";
function removeValFromArray(array, item) {
return array.filter((f) => f !== item);
}
export default function App() {
const [selectedColumns, setSelctedColumns] = useState([]);
function onHandler(col, checked) {
if (checked) {
if (!selectedColumns.includes(col)) {
setSelctedColumns([...selectedColumns, col]);
}
} else {
let temp = removeValFromArray(selectedColumns, col);
setSelctedColumns(temp);
}
}
return (
<div className="App">
<form>
<label>One</label>
<input
type="checkbox"
value="One"
checked={selectedColumns.includes("One")}
onChange={(e) => {
onHandler(e.target.value, e.target.checked);
}}
/>
<label>Two</label>
<input
type="checkbox"
value="Two"
checked={selectedColumns.includes("Two")}
onChange={(e) => {
onHandler(e.target.value, e.target.checked);
}}
/>
<label>Three</label>
<input
type="checkbox"
value="Three"
checked={selectedColumns.includes("Three")}
onChange={(e) => {
onHandler(e.target.value, e.target.checked);
}}
/>
</form>
<br />
<h3>Selected Columns</h3>
<ul>
{selectedColumns.map((col) => {
return <li>{col}</li>;
})}
</ul>
</div>
);
}
Demo - https://codesandbox.io/embed/nervous-wind-s0htq?fontsize=14&hidenavigation=1&theme=dark演示 - https://codesandbox.io/embed/nervous-wind-s0htq?fontsize=14&hidenavigation=1&theme=dark
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.