Search code examples
javascriptarraysreactjsnext.jsjavascript-objects

Get an array of strings from an array of objects with conditions


What is the best way to get an array of strings from an array of objects, where you can specify to only take value x where value y=z?

Current solution:

    array = [{
        "Item": "A",
        "Quantity": 2
      },
      {
        "Item": "B",
        "Quantity": 7
      },
      {
        "Item": "C",
        "Quantity": 7
      },
      {
        "Item": "D",
        "Quantity": 7
      },
      {
        "Item": "E",
        "Quantity": 7
      },
      {
        "Item": "F",
        "Quantity": 1
      }
    ];
    
    let filteredValues = array.map((el) => el.Quantity === 7 && el.Item);
    
    console.log(filteredValues)

Expected outcome:

["B", "C", "D", "E"]

Actual outcome:

[false, "B", "C", "D", "E", false]

Additional info: using next.js / react


Solution

  • Use Array.filter() along with Array.map()

    Working Demo :

    const array = [{
      "Item": "A",
      "Quantity": 2
    },             {
      "Item": "B",
      "Quantity": 7
    },             {
      "Item": "C",
      "Quantity": 7
    },{
      "Item": "D",
      "Quantity": 7
    },{
      "Item": "E",
      "Quantity": 7
    },{
      "Item": "F",
      "Quantity": 1
    }];
    
    const filteredValues = array.filter((el) => el.Quantity === 7).map(elem => elem.Item);
        
    console.log(filteredValues)