(Javascript) Determine if a numbervalue is contained or a number less than the numbervalue is contained in an array of objects

Viewed 65

I have an array of objects with arrays of consecutive integers, and an integer value:

const worlds = [
{levelnumbers: [0,1,2,3,4,5]},
{levelnumbers: [6,7,8,9,10]},
{levelnumbers: [11,12,13,14]}];

const reachedLevel = 9;

I want to determine if reachedLevel or a value lower than that is contained in each world object and set a locked value on each object.

I have tried this:

worlds.forEach(world => {
world.locked = !world.levelnumbers.includes(reachedLevel);
}
);

But is "locks" all worlds but the one containing the actual reached level. I want worlds[0] to have locked set to false even though levelReached is eg. 10.

4 Answers

You could have a look to the minimum of the numbers and check against your value.

const
    worlds = [{ levelNumbers: [0, 1, 2, 3, 4, 5] }, { levelNumbers: [6, 7, 8, 9, 10] }, { levelNumbers: [11, 12, 13, 14] }],
    reachedLevel = 9;

worlds.forEach(world => world.locked = Math.min(...world.levelNumbers) > reachedLevel);

console.log(worlds);
.as-console-wrapper { max-height: 100% !important; top: 0; }

You can check if all level numbers are greater than the reached level using Array#every and assign the result to the locked parameter.

const worlds = [
  {levelNumbers: [0,1,2,3,4,5]},
  {levelNumbers: [6,7,8,9,10]},
  {levelNumbers: [11,12,13,14]}
];

const reachedLevel = 9;

worlds.forEach(world => 
  world.locked = world.levelNumbers.every(n => n > reachedLevel) 
)

console.log(worlds);

First , check your javascript object. it contains levelnumbers and levelNumbers and both are not same.

Second - Instead of contains use include and what is contains though?

const worlds = [
{levelnumbers: [0,1,2,3,4,5]},
{levelnumbers: [6,7,8,9,10]},
{levelnumbers: [11,12,13,14]}];

const reachedLevel = 9;

worlds.forEach(world => {
  world.locked = world.levelnumbers.includes(reachedLevel)
}
);

console.log(worlds);

You have typos in the key names first 2 elements use levelnumbers but, last is levelNumbers. Also javascript does not have a contains function instead use the indexOf which returns -1 if element is not present.

Related