Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript-将数组项移动到数组的开头_Javascript_Arrays_Reactjs_Sorting_Lodash - Fatal编程技术网

JavaScript-将数组项移动到数组的开头

JavaScript-将数组项移动到数组的开头,javascript,arrays,reactjs,sorting,lodash,Javascript,Arrays,Reactjs,Sorting,Lodash,我有一个显示产品列表(带有renderSectionHeader)的SectionList。每个标题旁边都有一个星形图标,我想在按下该星形图标时重新排序类别。例如,如果用户同时点击汽车和建筑物,我希望这两个类别都移动到顶部 这是我的分区列表: <SectionList sections={this.state.products} renderSectionHeader={({section}) => ( <TouchableOpacity onP

我有一个显示产品列表(带有renderSectionHeader)的SectionList。每个标题旁边都有一个星形图标,我想在按下该星形图标时重新排序类别。例如,如果用户同时点击汽车和建筑物,我希望这两个类别都移动到顶部

这是我的分区列表:

<SectionList
    sections={this.state.products}
    renderSectionHeader={({section}) => (
        <TouchableOpacity onPress={()=>{this.sortFavorite(section.key)}}>
            <Text>{section.key}</Text>
            <FontAwesome name="star" color="grey" />
        </TouchableOpacity>
    )}
    renderItem={({item,index}) => (
        <Text>{item.name}<Text>
    )}
/>
这就是我最喜欢的类别列表:

0: {key: "Fruits", data: Array(1)}
1: {key: "Cars", data: Array(10)}
2: {key: "Buildings", data: Array(4)} 
["Cars","Buldings"]

如果有办法的话,我很乐意使用lodash。

您可以按类别列表排序,并使用收藏夹列表中类别键的索引对它们进行排序

常量类别=[
{键:“水果”,数据:数组(1)},
{键:“汽车”,数据:数组(2)},
{关键字:“建筑物”,数据:数组(1)},
{键:“废话”,数据:数组(1)}
];
const favoriteCatIds=[“建筑物”、“汽车”];
const sortedCategories=uu.sortBy(类别,(项目)=>{
const index=favoriteCatIds.indexOf(item.key);
返回索引==-1?类别。长度:索引;
});
控制台日志(分类目录)

您不需要使用lodash,只需要普通的排序

const favoriteCategoriesSet = new Set(favoriteCategories)
const sortedProductsTree = productsTree.sort((a, b) => favoriteCategoriesSet.has(b.key) - favoriteCategoriesSet.has(a.key))

真是太棒了!非常感谢。请允许我提最后一个问题。。您将如何根据阵列中最喜爱的类别更改星形图标的颜色?
const favoriteCategoriesSet = new Set(favoriteCategories)
const sortedProductsTree = productsTree.sort((a, b) => favoriteCategoriesSet.has(b.key) - favoriteCategoriesSet.has(a.key))