Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

158
Visualizações
Javascript arrays how to print sorted elements

I have a question about arrays. I'm new to javascript and I'm writing a program that has a function where it filters 20 elements of an array by category. That is, I have 3 buttons where, by clicking on one of them, the function is turned on and it starts displaying the filtered elements. Please tell me how can this be done? I have already tried a bunch of ways, but in the end nothing happened, although I think that I made a mistake somewhere.

array:

window.products = [
  {
    id: "i8",
    title: "Iphone 8",
    description:
      "The iPhone 8 ",
    price: 19900,
    discontinued: false,
    categories: ["c1"]
  },
  {
    id: "i10",
    title: "Iphone X",
    description: "Iphone 10",
    price: 39900,
    discontinued: false,
    categories: ["c1"]
  },
  {
    id: "i11",
    title: "Iphone 11",
    description: "The iPhone 11 ",
    price: 69900,
    discontinued: false,
    categories: ["c1"]
  };

my function

function myFunction() {
  document.getElementById("selected-category").innerHTML = "Iphones";
  document.getElementById("category-products").innerHTML = "";
  for (i = 0; i < 20; i++) {
    document.getElementById("category-products").innerHTML = window.id;
    const found = window.products.find(window.products.categories == "c1");
    console.log(found);
  }
}

part html code with button

<button onclick="myFunction()">Iphones</button>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

First, you have syntax error in your windows.products = [ ... };. It's not closed properly (you need a ] before the };.

Then, the find method needs to be passed a function that processes an element of the Array.
What you tried window.products.categories == "c1" evaluates to false, because the property categories does not exist in the window.products array. You get undefined on the left hand side and a string on the right hand side, so it's always false. You'd get "false is not a function".

Examples of using find() with a function:
const found = window.products.find( element => element.categories == "c1" );
or

const found = window.products.find( function(element) {
    return element.categories == "c1"
});

But then:

  1. The above == "c1" isn't what you should use, because it only matches due to type coercion from an array to a string, and only matches when the categories has only "c1" and no other elements. You should use includes method.
  2. "find" will only give you one matching product. Use "filter" to find all matching ones.
    If you only need to search for one key "c1", you can use const found = window.products.filter( product=> product.categories.includes("c1")); and for two keys "c1" and "c2": const found = window.products.filter( product => product.categories.includes("c1") && product.categories.includes("c2"));
    But I don't think you should use the above, because you should handle the case where the user searches for multiple keys.
const searchList = ['c1', 'c2', 'c3']
const found = window.products.filter ( function( product) {
//returns true if element.categories contains all of 'c1', 'c2' and 'c3'
 return searchList.every( searchKey => product.categories.includes(searchKey)) ;
}) 

You can also do the search in one line, but may be harder to read :

const searchList = ['c1', 'c2', 'c3']
const found = window.products.filter ( product => searchList.every( searchKey => product.categories.includes(searchKey)) );
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda