2

I'm trying to sort this JavaScript object so only certain rows are returned, the object:

const baseHeroes = [
  { name: "Batman", powers: ["Strength", "Intelligence"] },
  { name: "Superman", powers: ["Strength", "Flying"] },
  { name: "Spiderman", powers: ["Spider Sense", "Webs"] },
  { name: "The Flash", powers: ["Speed"] },
  { name: "Captain America", powers: ["Strength", "Shield"] },
];

I want to return only the rows that have the power "Strength" in the powers section, but to return the full row with all data, so I'd want to have this when finished:

const strongHeroes = [
  { name: "Batman", powers: ["Strength", "Intelligence"] },
  { name: "Superman", powers: ["Strength", "Flying"] },
  { name: "Captain America", powers: ["Strength", "Shield"] },
];

Any help would be greatly appreciated.

1
  • Do you know how to check whether a single array, like ["Strength", "Flying"], contains "Strength"? Commented Apr 30, 2019 at 22:46

2 Answers 2

4

Array.filter is your friend here. Alongside that, .includes is also your friend:

const baseHeroes = [
  { name: "Batman", powers: ["Strength", "Intelligence"] },
  { name: "Superman", powers: ["Strength", "Flying"] },
  { name: "Spiderman", powers: ["Spider Sense", "Webs"] },
  { name: "The Flash", powers: ["Speed"] },
  { name: "Captain America", powers: ["Strength", "Shield"] },
];

const results = baseHeroes.filter( h => h.powers.includes('Strength') );

console.log(results);

There are other things you might want to think about such as case sensitivity and the possibility of .powers being null or something other than an array, but this should give you a general idea of how to go about it.

Sign up to request clarification or add additional context in comments.

Comments

1

I'm extremely new to JavaScript, but the following seems to work.

const strongHeroes = [];

const baseHeroes = [
  { name: "Batman", powers: ["Strength", "Intelligence"] },
  { name: "Superman", powers: ["Strength", "Flying"] },
  { name: "Spiderman", powers: ["Spider Sense", "Webs"] },
  { name: "The Flash", powers: ["Speed"] },
  { name: "Captain America", powers: ["Strength", "Shield"] },
];

for (var i = 0; i < baseHeroes.length; i++) {
    if (baseHeroes[i].powers.indexOf("Strength") != -1) {
        strongHeroes.push(baseHeroes[i]);
    }
}

Basically it searches through the original array, and if the powers contains the string "Strength" it returns the location of the start of Strength, and if it doesn't find it, returns -1. So if we find Strength in the powers, push that array to a new array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.