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

时间:2019-10-05 01:57:41

标签: javascript arrays reactjs sorting lodash

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

这是我的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>
    )}
/>

首先,我创建了一个数组来存储/删除onPress上喜欢的类别:

sortFavorite = (currentCategory) => {
    let items = this.state.products
    let favouriteCategories = this.state.favouriteCategories
    let index = favouriteCategories.indexOf(currentCategory)

    if(index === -1){
      for(let i =0; i < items.length; i++){
        if(items[i].key === currentCategory){
          favouriteCategories.push(
            items[i].key
          )
        }
      }
    }
    else {
      favouriteCategories.splice(index, 1);
    }

    this.setState({favouriteCategories: favouriteCategories},()=>{
        // move to top of array
        const sortedCategories = _.sortBy(items, (item) => {
        const index = favouriteCategories.indexOf(item.key)
         return index == -1 ? items.length : index
        })
    })
  }

如何比较我的产品系列和我最喜欢的产品类别,然后重新订购产品系列?

这是我的一系列产品的外观:

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

这是我最喜欢的类别数组的样子:

["Cars","Buldings"]

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

2 个答案:

答案 0 :(得分:0)

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

const categories = [
  {key: "Fruits", data: Array(1)},
  {key: "Cars", data: Array(2)},
  {key: "Buildings", data: Array(1)},
  {key: "Blah", data: Array(1)}

];

const favoriteCatIds =  ["Buildings", "Cars"];

const sortedCategories = _.sortBy(categories, (item) => {
  const index = favoriteCatIds.indexOf(item.key);
  return index == -1 ? categories.length : index;
});

console.log(sortedCategories);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

答案 1 :(得分:0)

您不需要lodash,只需要普通排序

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