0

I am trying to compare these two nested arrays to ensure if they are the same but I couldn't figure it out, I tried to start but couldn't finish.

I need to make sure they have both the same food_names and the same ingredients in the selected_ingredients array.

Any help would be appreciated.

interface DataInterface {
    food_name: string,
    selected_ingredients: Array<string>
}

const orderFood: Array<DataInterface> = [
    {selected_ingredients: ["Tomatoes", "Lettuce", "Cheese"], food_name: "Single Burger"},
    {selected_ingredients: [], food_name: "Fountain Drink"}
];

const orderFood2: Array<DataInterface> = [
    {food_name: "Single Burger", selected_ingredients: ["Tomatoes", "Lettuce", "Cheese"]},
    {food_name: "Fountain Drink", selected_ingredients: []}
]

function isSame() {
    for(let i = 0; i < orderFood.length; i++) {
        
    }
    return false;
}
Colton
  • 1
  • Does this answer your question? [How to compare arrays in JavaScript?](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – hoangdv Aug 14 '20 at 01:59

1 Answers1

0

You can use lodash which has an _.isEqual method. This performs a deep equal on objects. Which will work on arrays as well. The only issue is sort order which isEqual wont check.

https://lodash.com/docs/4.17.15#differenceWith

There are some examples below using isEqual. I'll leave it to you to decide if you should sort prior to comparing. You'd need to deep sort, sorting the values of selected_ingredients as well as the orderFood array to get a relevant meaning form a deep compare.

const a = {food_name: "Single Burger", selected_ingredients: ["Tomatoes", "Lettuce", "Cheese"]}
const b = {food_name: "Fountain Drink", selected_ingredients: []}
const c = {food_name: "Fountain Drink", selected_ingredients: []}

console.log('compare different objects:', _.isEqual(a, b))
console.log('compare same objects:', _.isEqual(b, c))


const orderFood = [
  {selected_ingredients: ["Tomatoes", "Lettuce", "Cheese"], food_name: "Single Burger"},
  {selected_ingredients: [], food_name: "Fountain Drink"}
]

const orderFood2 = [
    { food_name: "Single Burger", selected_ingredients: ["Tomatoes", "Lettuce", "Cheese"] },
    {food_name: "Fountain Drink", selected_ingredients: []}
]

console.log('compare same array of object:', _.isEqual(orderFood, orderFood2))

const orderFood3 = [
    {food_name: "Fountain Drink", selected_ingredients: []},
    {food_name: "Single Burger", selected_ingredients: ["Tomatoes", "Lettuce", "Cheese"] }
]

console.log('compare same array of object with different order:', _.isEqual(orderFood2, orderFood3))
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>
Lex
  • 4,749
  • 3
  • 45
  • 66