When attempting to transfer elements from one array to another, the issue that arises is the error message stating 'Expected identifier'

My code is working fine in every browser except for IE. I'm unsure how to fix the issue.

I am trying to remove an item from one array and place it at the top of another array.

Currently, I have an array of articles where some are marked as hero and others are not. I want to locate the first hero article in the array, remove it, and then move it to the beginning of another array.

The error message I am receiving is 'Expected identifier'.

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 (var [i, article] of articles.entries()) {
  if (article.hero) {
    heros.unshift(article);
    articles.splice(i, 1);
    break;
  }
}

console.log(heros);
console.log(articles);

Answer №1

Optimizing for IE browser: utilize a simple for loop.

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=0;i<articles.length;i++){

  if(articles[i].hero)
    {
    heros.unshift(articles[i]);
    articles.splice(i, 1);
    break;
    }
}

console.log(heros);
console.log(articles);

Answer №2

Give this solution a try:

const posts = [
    {title: "post 1", featured: false},
    {title: "post 2", featured: false},
    {title: "post 3", featured: true},
    {title: "post 4", featured: false},
    {title: "post 5", featured: true},
    {title: "post 6", featured: false},
    {title: "post 7", featured: true},
];

const featuredPosts = [];

Object.keys(posts).forEach(function(post) {
  var item = posts[post];
  if (item != undefined && item.featured) {
    featuredPosts.unshift(item);
    posts.splice(post, 1);
  }
});

console.log(featuredPosts);
console.log(posts);

Answer №3

My rendition

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},
];

let heros = [];
let i = -1;
articles.some(function(article) { i++; return article.hero; })
if (i>=0) {
  heros.push(articles[i]); 
  articles.splice(i,1);
}

console.log(heros);
console.log(articles);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I adjust the vertical position of Material-UI Popper element using the popper.js library?

https://i.stack.imgur.com/ZUYa4.png Utilizing a material-ui (v 4.9.5) Popper for a pop-out menu similar to the one shown above has been my recent project. The anchorElement is set as the chosen ListItem on the left side. My goal is to have the Popper alig ...

What is the best way to store multiple parameters as a single parent parameter in jQuery?

Here is the current code snippet: $(this.form).attr("action",$(this.form).attr("action") + '?' + $("#sortable").sortable('serialize') + "&foo[]=bar"); This code generates the following output: importance[]=1&importance[]=2&am ...

Tips for Altering Information within a Text Box

Below is a snippet of HTML code that needs to be modified: <td class="targetTD"> <a href="http://foo.com"> <span>content</span> </a> **Text I want to modify** <span>more content</span> </td> The ...

How come the date is not showing up inside the <p> tag?

Check out this snippet of HTML code: <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="bootstrap_4.5.0&bsol ...

Incorporating External JavaScript and CSS specifically for a single component

In my Angular 4 application, I have a specific component that requires the use of a js and css file. While most guidelines suggest placing these files in the Index.html file, I prefer to only load them when this particular component is accessed, not on e ...

The directionalLight Properties do not yield any visible results

I recently experimented with the parameters in this code snippet but did not see any visible changes. The values for directionalLight.shadowCameraVisible, directionalLight.shadowCameraLeft, directionalLight.shadowCameraRight, directionalLight.shadowCameraB ...

Maximizing Angular and Require's Potential with r.js

I'm facing some challenges while setting up r.js with require in my Angular application. As I am new to AMD, solving this issue might be a simple task for someone experienced. However, I need to maintain the current directory structure as it allows me ...

The issue with the callback function not being triggered within a self-repeating loop

As I work on creating a user-script to incorporate a trailer video into a website, I encountered an issue with the callback function in my script. The goal is to filter the real source of the video from different URL formats, but for some reason, the callb ...

What is the best way to sift through an array containing arrays?

Looking for help with filtering and pushing data from a JSON array? Specifically, I need to filter arrays where the data's attrs property includes a src attribute. It's proving challenging for me, so any assistance would be greatly appreciated. ...

Combining two arrays based on a common id

Here are two arrays: var members = [{docId: "1234", userId: 222}, {docId: "1235", userId: 333}]; var memberInfo = [{id: 222, name: "test1"}, {id: 333, name: "test2"}]; I want to merge them into a single array by matching user ids programmatically. The c ...

Extract JSON Data from Nested Object

I'm currently struggling with parsing JSON data from an object within an object using a Node.js script. Here's the JSON Object: { "Item":{ "job_change_request":"task0020764", "id":"a156fc4e-e8d4-424f-a792-0c8cf8e3ca46", ...

Whenever I try to include a new array in my multidimensional array, it seems like an additional "A" keeps popping up at the start. Can anyone explain why this is happening?

I am experiencing a strange issue. In my SQL database, I have a multidimensional array to which I add new arrays weekly using a cron job. While this process usually runs smoothly, sometimes a random A gets inserted into the array when a new one is added. T ...

Regular expression: match all content up to a certain word(s)

I have two different versions of a string that look like this: The Student's Companion *Author: Alcock, Pete;May, Margaret;Wright, Sharon*MIL EAN/ISBN: 9781283333115 Java Programming: Java Expert*Author:Sarang, Poornachandra*MIL EAN/ISBN: 978128011 ...

What are the steps to customizing a package on atmospherejs.com within meteor.js?

When working with atmosphere in meteor.js, installing a package is typically as simple as using a single command. However, if there is a need to make changes to a specific package for customization purposes, the process becomes a bit more complex. For ex ...

Acquire the Information from a Textarea That Has Been Edited by the User

My challenge lies in taking user-entered text from a content editable textarea and sending it via POST request, but the fields edited by the user are returning with an empty textContent. The code snippet below shows that each .entryRow (obj) contains multi ...

What is the best way to extract a list of particular items from a nested array?

When I execute the following code: var url="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=categories&titles=Victory_Tests&callback=?"; $.getJSON(url,function(data){ $.each(data, function(i, item) { console.lo ...

AngularJS: Hide Row in NG-Grid Based on Condition

I am a beginner in angularJS and I have a requirement to hide a row in my ng-grid table if the value of a column is '0'. The grid consists of 4 columns: User Today This Week This Month I need to hide an entire row if the value in the 'Th ...

Can you explain the significance of angle brackets in JavaScript?

After examining the JSX code example provided, I found it to be quite intriguing. const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })<AppBarProps>(({ theme, open }) => ({ zIndex: theme.zIndex.drawer ...

Implementing double parentheses in the source code of an AngularJS input directive using JavaScript

I came across some unfamiliar syntax in the angularJs source code. Can someone provide an explanation for the expression within the parentheses of logical operators and dependency injection in "(inputType[lowercase(attr.type)] || inputType.text)(scope, ele ...

Filtering parameters in a Mongoose array

Consider the mongoose model below: var Product = new Schema({ eanCode: String, brandName: String, productNameNl: String, sex: String, suggestedRetailPrice: Number }) I am looking to create a function that can query this model using an arra ...