-1

I have following array

 let newArray = [
    {
      "conterTop": {
        "uncategroized": [item1, item2, item3],
        "categroized": [item4, item5]
      }
    },
    {
      "flooring": {
        "uncategroized": [item1, item2, item3],
        "categroized": [item4, item5]
      }
    }
]

I'm pushing countertop & flooring on runtime. Now I need to check if countertop already exists in newArray, it should not push countertop again. I have tried newArray.includes() but it's not working. Please any suggestion?

Liftoff
  • 24,717
  • 13
  • 66
  • 119
Ahmed Malik
  • 159
  • 10
  • 1
    Does this answer your question? [How do I check if an array includes a value in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-a-value-in-javascript) Specifically look at the 2nd top answer as it deals with non primitive types – Krzysztof Krzeszewski Dec 11 '20 at 10:03
  • This might help you. https://stackoverflow.com/a/57659626/12960148 – Htet Phyo Naing Dec 11 '20 at 10:07

3 Answers3

0

You can filter the array to look for your matching key and check the length of the filtered array. If the length is greater than 0, it exists. If not, it doesn't.

newArray.filter(x => return typeof(x.countertop) !== "undefined").length > 0
Liftoff
  • 24,717
  • 13
  • 66
  • 119
0

Here I just filtered out every value that doesn't have counterTop and check if any value left

let newArray = [{
    "conterTop": {
      "uncategroized": [1, 2, 3],
      "categroized": [4, 5]
    }
  },
  {
    "flooring": {
      "uncategroized": [1, 2, 3],
      "categroized": [4, 5]
    }
  }
];

let isCounterTopExists = newArray.filter(x => x.conterTop).length > 0
console.log(isCounterTopExists);
Omri Attiya
  • 3,917
  • 3
  • 19
  • 35
0

This is what Array.prototype.some is for:

let newArray = [
    {
      "conterTop": {}
    },
    {
      "flooring": {}
    }
];

let testArray = [
  {
    "flooring": {}
  }
];

const testArrayResult = testArray.some(obj => obj.conterTop);
const newArrayResult = newArray.some(obj => obj.conterTop);

console.log("testArray has 'conterTop':", testArrayResult);
console.log("newArray has 'conterTop':", newArrayResult);
Lennholm
  • 7,205
  • 1
  • 21
  • 30