为了账号安全,请及时绑定邮箱和手机立即绑定

将数组中的项目移动到javascript中的顶部

将数组中的项目移动到javascript中的顶部

慕容708150 2021-07-02 14:05:19
我需要从一个数组中删除一个项目,然后将其放入另一个数组的顶部。我目前有一系列文章,其中一些文章的类型英雄是真实的,而其他文章则是常规的。我需要找到数组中的第一篇英雄文章并将其删除。然后把这篇文章放到另一个数组的顶部。任何帮助将非常感激。谢谢我目前有这个:articles = [    {title: "article 1", hero: false},    {title: "article 2", hero: false},    {title: "article 3", hero: true},    {title: "article 4", hero: false},    {title: "article 5", hero: true},    {title: "article 6", hero: false},    {title: "article 7", hero: true}]但想要这个结果:articles = [    {title: "article 1", hero: false},    {title: "article 2", hero: false},    {title: "article 4", hero: false},    {title: "article 5", hero: true},    {title: "article 6", hero: false},    {title: "article 7", hero: true}]hero = [    {title: "article 3", hero: true}]
查看完整描述

3 回答

?
白衣染霜花

TA贡献1796条经验 获得超10个赞

试试这个:


const articles = [

    {title: "article 1", hero: false},

    {title: "article 2", hero: false},

    {title: "article 3", hero: true},

    {title: "article 4", hero: false},

    {title: "article 5", hero: true},

    {title: "article 6", hero: false},

    {title: "article 7", hero: true},

];


const heros = [];


for(let [i, article] of articles.entries())

{

  if(article.hero)

    {

    heros.unshift(article);

    articles.splice(i, 1);

    break;

    }

}


console.log(heros);

console.log(articles);


查看完整回答
反对 回复 2021-07-08
?
慕的地8271018

TA贡献1796条经验 获得超4个赞

您可以使用.findIndex()来获取英雄等于 的第一篇文章true。然后,您可以使用此索引将对象添加到hero数组中,然后再次使用它从articles数组中删除.splice()。


请参阅下面的示例:


const articles = [

    {title: "article 1", hero: false},

    {title: "article 2", hero: false},

    {title: "article 3", hero: true},

    {title: "article 4", hero: false},

    {title: "article 5", hero: true},

    {title: "article 6", hero: false},

    {title: "article 7", hero: true}

];

const hero = [];

const foundArticle = articles.findIndex(({hero}) => hero);

hero.push(articles[foundArticle]);

articles.splice(foundArticle, 1);


console.log(articles);

console.log(hero);

对于 IE 支持,您可以手动查找索引而不是使用.findIndex():

function findObjInArr(arr, cb) {

  for(let i = 0; i < arr.length; i++) {

    let obj = arr[i];

    if(cb(obj)) {

      return i;

    }

  }

  return -1;

}


const articles = [

    {title: "article 1", hero: false},

    {title: "article 2", hero: false},

    {title: "article 3", hero: true},

    {title: "article 4", hero: false},

    {title: "article 5", hero: true},

    {title: "article 6", hero: false},

    {title: "article 7", hero: true}

];


const hero = [];

const foundArticle = findObjInArr(articles, function(obj) {

  return obj.hero;

});

hero.push(articles[foundArticle]);

articles.splice(foundArticle, 1);


console.log(articles);

console.log(hero);


查看完整回答
反对 回复 2021-07-08
  • 3 回答
  • 0 关注
  • 163 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信