1

I have an Array, like this one:

let myarr = [
  {type:"a", class:"x", value:"p"},
  {type:"b", class:"x", value:"r"},
  {type:"a", class:"y", value:"p"}
];

I need to use Array.includes to check whether an object with class=y is in this array.

I need to check it with myarr.includes({condition});

I could simply compare the whole object but I don't know how to use a key of the object to check.

4
  • it does not work with includes. you need a different approach. why includes? Commented Sep 6, 2018 at 11:13
  • Why are you using .includes() for that? Is this a requirement? Commented Sep 6, 2018 at 11:13
  • Why would you need to check it with myarr.includes? Thats not the right method for the job Commented Sep 6, 2018 at 11:13
  • myarr.some(x=>x.class=='y')?? Commented Sep 6, 2018 at 11:14

6 Answers 6

7

To do this you can use the some() method.

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

let myarr = [
  {type: "a",class: "x",value: "p"},
  {type: "b",class: "x",value: "r"},
  {type: "a",class: "y",value: "p"}
];

let pass = myarr.some(item => item.class == 'y');
let fail = myarr.some(item => item.class == 'z');

console.log(pass);
console.log(fail);

Sign up to request clarification or add additional context in comments.

Comments

2

Array.prototype.includes relies on identity checks which requires you to pass in the same object (not just an object with the same properties, it needs the same reference such that objA === objB). You want a function that allows you to provide a function in which you can check the condition. Fortunately there is Array.prototype.some for this ask.

myarr.some(item => item.class === 'y')

Comments

1

You may either use Array#some or you may also take advantage of using proper data structures.

Array#some

const myArr = [{
    type: "a",
    class: "x",
    value: "p"
  },
  {
    type: "b",
    class: "x",
    value: "r"
  },
  {
    type: "a",
    class: "y",
    value: "p"
  }
]

const hasClassY = myArr.some (o => o.class == 'y')
console.log (hasClassY)

Map instead of Array

const classMap = new Map([
  ['x', [{
    type: "a",
    class: "x",
    value: "p",

  }, {
    type: "b",
    class: "x",
    value: "r"
  }]],

  ['y', [{
    type: "a",
    class: "y",
    value: "p"
  }]]
])

if (classMap.has('y')) {
  // Do stuff here
}

const itemsWithYClass = classMap.get('y')
const itemsWithXClass = classMap.get('x')

const flatten = xs => [...xs].reduce((r, el) => [...r, ...el])

const allItems = flatten(classMap.values())

console.log('Y class: ', itemsWithYClass)
console.log('X class: ', itemsWithXClass)
console.log('All: ', allItems)

Specialized Map

class SpecializedMap extends Map {
  get[Symbol.species]() {
    return Map
  }

  getAll() {
    return [...this.values()].reduce((r, el) => [...r, ...el])
  }
}


const classMap = new SpecializedMap([
  ['x', [{
    type: "a",
    class: "x",
    value: "p",

  }, {
    type: "b",
    class: "x",
    value: "r"
  }]],

  ['y', [{
    type: "a",
    class: "y",
    value: "p"
  }]]
])

if (classMap.has('y')) {
  // Do stuff here
}

const itemsWithYClass = classMap.get('y')
const itemsWithXClass = classMap.get('x')
const allItems = classMap.getAll()


console.log('Y class: ', itemsWithYClass)
console.log('X class: ', itemsWithXClass)
console.log('All: ', allItems)

Array + Set

const myArr = [{
    type: "a",
    class: "x",
    value: "p"
  },
  {
    type: "b",
    class: "x",
    value: "r"
  },
  {
    type: "a",
    class: "y",
    value: "p"
  }
]

// This set contains all unique classes within myArr
// The challenge is you need to sync myArr with classSet
// so classSet contains the actual classes within myArr.
const classSet = new Set(['x', 'y'])

// Somewhere in your code you import classSet and...

if (classSet.has('y')) {
  console.log('Do stuff here!')
}

Comments

1

Try this simple solution.

let myarr = [
  {type:"a", class:"x", value:"p"},
  {type:"b", class:"x", value:"r"},
  {type:"a", class:"y", value:"p"}
];

console.log(myarr.some(function(element){return element["class"] === "x";}))

Comments

0

You could use Array.prototype.includes() or String.prototype.includes() but is not practical, and is not useful as a general solution in this case, see this:

let myarr = [
    {type:"a", class:"x", value:"p"},
    {type:"b", class:"x", value:"r"},
    {type:"a", class:"y", value:"p"}
  ];

//String.includes - We need the exact match, this could lead to error  
var value1 = JSON.stringify(myarr).includes('"class":"x"');

//Array.includes - It's ok, but it has two iterations, not one as some()
var value2 = myarr.map(o=>o.class).includes("x")

console.log(value1)
console.log(value2)

That is why using Some(), as other users said, is the better choice.

Comments

-2

I use lodash .includes() or .has() methods for things like that:

_.includes({ 'a': 1, 'b': 2 }, 1);

https://lodash.com/docs/4.17.10#includes

You can also do this with a plain js map, some or other methods.

2 Comments

Generally, unless the OP specifies otherwise, it's best to avoid needing a library in your answer. A good way to improve this answer would be to acknowledge some() and then add lodash as a suggestion after the fact.
@AndrewBone ye, i understand, but its still nothing wrong to know, u can do it fast with lodash. Cause sometimes u have "2 mins" (not 2 hours looking for plain js solutions) to push changes:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.