Home > Blockchain >  Javascript Searching for Index number of Array
Javascript Searching for Index number of Array

Time:04-15

I would be very grateful if you could help me. I've been sitting here for 5 hours and can't find a solution. I want to get the number in the array based on the name of the array (ex. "Apfelkuchen"). In this case, "Apfelkuchen" would be number 0.

I know that the indexOF method is used for this, but unfortunately I don't know. How to use it, because my array is not the usual case.

let Essen = [

    { name: "Apfelkuchen", ingredients: ["Apfel", "Mehl", "Zucker"] },
    { name: "Bananenkuchen", ingredients: ["Banane", "Mehl", "Zucker"] },
    { name: "Käsekuchen", ingredients: ["Köse", "Mehl", "Zucker"] },
    { name: "Steuselkuchen", ingredients: ["Steuselkuchen", "Mehl", "Zucker"] },
    { name: "Schokokuchen", ingredients: ["Schoko", "Mehl", "Zucker"] },
    { name: "Kürbiskuchen", ingredients: ["Kürbis", "Mehl", "Zucker"] },
    { name: "Zitronenkuchen", ingredients: ["Zitronen", "Mehl", "Zucker"] },
    { name: "Erdbeerkuchen", ingredients: ["Erdbeere", "Mehl", "Zucker"] },
    { name: "Nusskuchen", ingredients: ["Nuss", "Mehl", "Zucker"] },
    { name: "Butterkuchen", ingredients: ["Butter", "Mehl", "Zucker"] },

];

function createEssen(_name, _ingredients) {
    Essen.push({name: _name, ingredients: _ingredients})
}

function addIngredients(_name) {
    Essen[10].ingredients.push(_name)
}

function searchArrayNumber(_name) {
    
How????

}

CodePudding user response:

You can use .findIndex():

let Essen = [

    { name: "Apfelkuchen", ingredients: ["Apfel", "Mehl", "Zucker"] },
    { name: "Bananenkuchen", ingredients: ["Banane", "Mehl", "Zucker"] },
    { name: "Käsekuchen", ingredients: ["Köse", "Mehl", "Zucker"] },
    { name: "Steuselkuchen", ingredients: ["Steuselkuchen", "Mehl", "Zucker"] },
    { name: "Schokokuchen", ingredients: ["Schoko", "Mehl", "Zucker"] },
    { name: "Kürbiskuchen", ingredients: ["Kürbis", "Mehl", "Zucker"] },
    { name: "Zitronenkuchen", ingredients: ["Zitronen", "Mehl", "Zucker"] },
    { name: "Erdbeerkuchen", ingredients: ["Erdbeere", "Mehl", "Zucker"] },
    { name: "Nusskuchen", ingredients: ["Nuss", "Mehl", "Zucker"] },
    { name: "Butterkuchen", ingredients: ["Butter", "Mehl", "Zucker"] },

];


console.log(Essen.findIndex(x => x.name == "Apfelkuchen"));

  • Related