My goal is to click on each item, and the selected item should move to the top of the list and be rendered at the top. However, I encountered an issue where when clicking on an item, it moves to the top but the item that replaces it also gets checked.
Below is the code snippet:
<script>
let newData = [
{
Id: '1',
Name: 'a',
Group: 'GroupA'
},
{
Id: '2',
Name: 'b',
Group: 'GroupB',
selected: false
},
{
Id: '3',
Name: 'c',
Group: 'GroupC'
},
{
Id: '4',
Name: 'd',
Group: 'GroupD'
},
{
Id: '5',
Name: 'e',
Group: 'GroupA'
},
{
Id: '6',
Name: 'f',
Group: 'GroupA'
},
{
Id: '7',
Name: 'g',
Group: 'GroupB'
},
{
Id: '8',
Name: 'h',
Group: 'GroupC'
}
];
// Separate the data by Group
let groupData = {};
newData.forEach((item) => {
const { Group } = item;
if (!groupData[Group]) {
groupData[Group] = [];
}
groupData[Group].push(item);
});
// Function to handle checkbox click
function handleCheckboxClick(item) {
item.selected = !item.selected;
// Move selected item to the top of its Group list
const Group = item.Group;
const index = groupData[Group].findIndex((data) => data.Id === item.Id);
groupData[Group].splice(index, 1);
groupData[Group].unshift(item);
}
</script>
{#each Object.keys(groupData) as Group}
<h3>{Group}</h3>
<div>
{#each groupData[Group] as item}
<label>
<input
type="checkbox"
bind:checked={item.selected}
on:click={() => handleCheckboxClick(item)}
/>
{item.Name}
</label>
{/each}
</div>
{/each}
<style>
h3 {
margin-top: 20px;
}
div {
display: flex;
flex-direction: column;
}
</style>
https://stackblitz.com/edit/node-cjqvpz?file=src%2Froutes%2F%2Bpage.svelte