Sierra117-95
Sierra117-95

Reputation: 21

Filtering object based on partial string matching in JavaScript

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.

Upvotes: 2

Views: 2824

Answers (2)

Highlow
Highlow

Reputation: 11

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.

Upvotes: 1

mwilson
mwilson

Reputation: 12930

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.

Upvotes: 4

Related Questions