I want to make an alphabet index for businesses, and struggling to eliminate the duplicate. Like below:
T
Toy Store 1
Toy Store 2
Toy Store 3
So I sliced the initial letter of the business and want to delete it if the letter is already shown like below:
T
Toy Store 1
T // <- want to delete
Toy Store 2
T // <- want to delete
Toy Store 3
I tried using new Set but it does not work. I also tried using indexOf and filter method but didn't work either. Appreciate any help.
Component ListItem
export default function CatListItem(props) {
const {image,title,slicedInitial,onPress} = props;
return (
<View>
<Text>
{slicedInitial}
</Text>
<Text>
{title}
</Text>
</View>
);
};
Screen:
const renderList = () => {
//does not work
const indexedSlicedInitial=(item)=>{
const slicedInital=item.title.slice(0,1)
const index = [...new Set(slicedInital)]
return index
}
//
return (
<View>
{
<Animated.FlatList
data={data.list}
key={"list"}
keyExtractor={(item, index) => `list ${index}`}
renderItem={({ item, index }) => (
<ListItem
list
title={item.title}
slicedInitial={() => indexedSlicedInitial(item)}
onPress={() => onProdDetail(item)}
/>
/>
);
};
Use state in screen component to store prevIndex so, that you can compare everytime you get newIndex.
If they are not same then only return new index otherwise return empty string. On ListItem component render text only if its not an empty string.
Screen:
// use state to store prev value
const [prevIndex, setPrevIndex] = useState('')
const renderList = () => {
const indexedSlicedInitial=(item)=>{
const slicedInital=item.title.slice(0,1)
// if they are different then only return new index
if(prevIndex !== slicedInitial) {
setPrevIndex(slicedInitial)
return slicedInitial
}
// if slicedInitial same as prevIndex
return "";
}
// no changes below
Component ListItem:
export default function CatListItem(props) {
const {image,title,slicedInitial,onPress} = props;
return (
<View>
// only output slicedInitial if not empty
{slicedInitial ? <Text>
{slicedInitial}
</Text> : null}
<Text>
{title}
</Text>
</View>
);
};