0

I am new to the forum and a beginner at JavaScript. Please look at my code below that I am facing a problem with in terms of the output -

let myColor = ["Red", "Green", "White", "Black"];
console.log(myColor.toString());
console.log(myColor.join("+"));
let strings = ["avengers", "captain america", "ironman", "black panther"];
const newStrings = strings.map(elements => { 
    return elements.toUpperCase()}
);
console.log(newStrings);

const heroes = [
    {name: "Spider-Man"},
    {name: "Thor"},
    {name:"Black Panther"},
    {name: "Captain Marvel"},
    {name: "Silver Surfer"}
];

heroes.forEach(function(o) {
  o.hero = o.name;
  delete o.name;
});

let heroesName = [];
for(var i=0; i<heroes.length; i++) {
    heroesName.push(heroes[i]); heroesName[i].id=i;
};
console.log(heroesName);

const inputWords = ["spray", "limit", "elite", "exuberant", "destruction", "present"];
console.log(inputWords.splice(3,5));

With the above-mentioned code I am getting the below-mentioned output -

Red,Green,White,Black
Red+Green+White+Black
[ 'AVENGERS', 'CAPTAIN AMERICA', 'IRONMAN', 'BLACK PANTHER' ]
[
  { hero: 'Spider-Man', id: 0 },
  { hero: 'Thor', id: 1 },
  { hero: 'Black Panther', id: 2 },
  { hero: 'Captain Marvel', id: 3 },
  { hero: 'Silver Surfer', id: 4 }
]
[ 'exuberant', 'destruction', 'present' ]

However, I am trying to get the output as follows -

Red,Green,White,Black
Red+Green+White+Black
[ 'AVENGERS', 'CAPTAIN AMERICA', 'IRONMAN', 'BLACK PANTHER' ]
[
  { id: 0, hero: 'Spider-Man' },
  { id: 1, hero: 'Thor' },
  { id: 2, hero: 'Black Panther' },
  { id: 3, hero: 'Captain Marvel' },
  { id: 4, hero: 'Silver Surfer' }
]
[ 'exuberant', 'destruction', 'present' ]

What is it that I am doing wrong over here? So, all I want is the ID property in the object array called heroes to be before the hero name and not after. Could someone guide me?

Viraj
  • 3
  • 4
  • 1
    Since it is a JSON, `{ id: 0, hero: 'Spider-Man' }` is the same as `{ hero: 'Spider-Man', id: 0 }`. The order does not matter. What you have done is correct. Can check out this answer for further information https://stackoverflow.com/questions/16870416/does-the-sequence-of-the-values-matter-in-a-json-object – Aneesh May 01 '22 at 21:15
  • There's no JSON here, just an array of objects. But the point stands, order of properties is not important, nor should they be relied on even though modern javascript does provide consistent ordering. See: [Does JavaScript guarantee object property order?](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – pilchard May 01 '22 at 21:22

1 Answers1

1

It doesn't matter what order the properties are in. Still if you want to change the order, you can change a line in your for loop

let heroesName = [];
for(let i=0; i<heroes.length; i++) {
       heroesName.push({ id: i, hero: heroes[i].hero });
};
console.log(heroesName);

Inder
  • 1,711
  • 1
  • 3
  • 9