Check existince in 2d array

I have a 2d array such as a list of cars for sale:

[ 
  ["honda", "red", 1977, "USD 15k"],
  ["honda", "blue", 2004, "USD 14k"],
  ["Volkswagen", "blue", 2005, "USD 22k"],
  ["Volkswagen", "grey", 2012, "USD 30k"],
  ["Dodge", "yellow", 1985, "USD 10k"],
];

How can I check that for a given colour (e.g., blue) a given car (e.g., Honda) exists?

I can create a loop, but I am sure that more elegant solutions exist.

resultArray = sourceArray.filter((e) =>
{
    return e.includes("blue");
}

Dear Thallius,

Many thanks! However:

  1. How can we make sure that for the colours it only looks at the 2nd element of each array? (In theory a car brand could equal a colour)
  2. How do we then check if also the car brand exists for that colour (i.e., Honda)?

Kind regards

You said you can do it with a loop. So you should know how to check only the second element of an array instead of using include which checks all elements. Same for car type.

If I understand right, you can use Array.some

const cars = [ 
  ["honda", "red", 1977, "USD 15k"],
  ["honda", "blue", 2004, "USD 14k"],
  ["Volkswagen", "blue", 2005, "USD 22k"],
  ["Volkswagen", "grey", 2012, "USD 30k"],
  ["Dodge", "yellow", 1985, "USD 10k"],
];

const findCar = function (make, colour, cars = []) {
    // convert given properties to match into lower case
    const targetMake = make.toLowerCase()
    const targetColour = colour.toLowerCase()
    
    return cars.some((car) => {
        // assign first two indexes to variables in lower case
        const carMake = car[0].toLowerCase()
        const carColour = car[1].toLowerCase()

        return carMake === targetMake && carColour === targetColour
    })
}

console.log(findCar("honda", "red", cars)) // true
console.log(findCar("honda", "green", cars)) // false
console.log(findCar("dodge", "yellow", cars)) // true
console.log(findCar("Volkswagen", "red", cars)) // false

You will see I have also made use of toLowerCase as the source data and maybe the values being used to find a match are inconsistent e.g. honda, Volkswagen

Note: It would be nicer to work with if your data made use of objects e.g. it came in a JSON format like this

[
    { 
        make: "honda",
        colour: "red",
        year: 1977,
        price: 15000,
        currency: "USD"
    },
    { 
        make: "honda",
        colour: "blue",
        year: 2004,
        price: 14000,
        currency: "USD"
    },
    ...
    { 
        make: "dodge",
        colour: "yellow",
        year: 1985,
        price: 10000,
        currency: "USD"
    }
]

Dear RPG,

that is great help, many thanks!!!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.