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

我需要从一个数组中删除一个项目,然后将其放入另一个数组的顶部。


我目前有一系列文章,其中一些文章的类型英雄是真实的,而其他文章则是常规的。我需要找到数组中的第一篇英雄文章并将其删除。然后把这篇文章放到另一个数组的顶部。任何帮助将非常感激。谢谢


我目前有这个:


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}

]


慕容708150
浏览 164回答 3
3回答

白衣染霜花

试试这个: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);

慕的地8271018

您可以使用.findIndex()来获取英雄等于 的第一篇文章true。然后,您可以使用此索引将对象添加到hero数组中,然后再次使用它从articles数组中删除.splice()。请参阅下面的示例:const articles = [&nbsp; &nbsp; {title: "article 1", hero: false},&nbsp; &nbsp; {title: "article 2", hero: false},&nbsp; &nbsp; {title: "article 3", hero: true},&nbsp; &nbsp; {title: "article 4", hero: false},&nbsp; &nbsp; {title: "article 5", hero: true},&nbsp; &nbsp; {title: "article 6", hero: false},&nbsp; &nbsp; {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) {&nbsp; for(let i = 0; i < arr.length; i++) {&nbsp; &nbsp; let obj = arr[i];&nbsp; &nbsp; if(cb(obj)) {&nbsp; &nbsp; &nbsp; return i;&nbsp; &nbsp; }&nbsp; }&nbsp; return -1;}const articles = [&nbsp; &nbsp; {title: "article 1", hero: false},&nbsp; &nbsp; {title: "article 2", hero: false},&nbsp; &nbsp; {title: "article 3", hero: true},&nbsp; &nbsp; {title: "article 4", hero: false},&nbsp; &nbsp; {title: "article 5", hero: true},&nbsp; &nbsp; {title: "article 6", hero: false},&nbsp; &nbsp; {title: "article 7", hero: true}];const hero = [];const foundArticle = findObjInArr(articles, function(obj) {&nbsp; return obj.hero;});hero.push(articles[foundArticle]);articles.splice(foundArticle, 1);console.log(articles);console.log(hero);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript