Home > OS >  Accessing boolean values within objects in an array
Accessing boolean values within objects in an array

Time:03-12

Hi I am a beginner learning javascript (this is my first question) and have spent hours trying to solve the below. Can't find a answer online, so any help would be so much appreciated :)

I have a list of books which are objects within an array. The properties are the name (value is a string) and whether or not the book is Best-Selling (value is a boolean). See below

const books = [
{ name: 'Book 1',
bestSelling: true,},
{ name: 'Book 2',
bestSelling: false,},
{ name: 'Book 3',
bestSelling: true,},
];

What I am trying to do is access the bestSelling values from the array. Firstly how would I do this.

Secondly, how would I write a function which if there was at least one book which wasn't best selling would return false overall, and if every item within the array was best-selling would return true?

I have come up with the following but it does not seem to work:

let won = 0
for (let i = 0; i> books.length; i  ) {
if (books[I].bestSeller === false) {
return false;
}
} return true;
} 

Any ideas? Thanks in advance.

CodePudding user response:

Use books[index].bestSelling to access the booleans and, you can use Array#every() to check if all books are best selling - return true - otherwise return false.

const books = [
    { name: 'Book 1', bestSelling: true},
    { name: 'Book 2', bestSelling: false},
    { name: 'Book 3', bestSelling: true}
];

//accessing booleans books[i].bestSelling eg
console.log( books[0].bestSelling );

//function to return true only if all books are best selling
function isBestSeller(books) {
    return books.every(book => book.bestSelling);
}

console.log( isBestSeller( books ) );

NOTE:

return books.every(book => book.bestSelling); is equivalent to:

return books.every(function(book) {
    return book.bestSelling;
});

And the whole function can be re-written as:

const isBestSeller = books => books.every(book => book.bestSelling);

CodePudding user response:

What I am trying to do is access the bestSelling values from the array. Firstly how would I do this.

You can achieve that via using Array.filter() method.

const books = [
{ name: 'Book 1',
bestSelling: true,},
{ name: 'Book 2',
bestSelling: false,},
{ name: 'Book 3',
bestSelling: true,},
];

const bestSellingBooks = books.filter((obj) => obj.bestSelling);

console.log(bestSellingBooks);

Secondly, how would I write a function which if there was at least one book which wasn't best selling would return false overall, and if every item within the array was best-selling would return true ?

You can achieve this by using Array.some() method.

const books = [
{ name: 'Book 1',
bestSelling: true,},
{ name: 'Book 2',
bestSelling: false,},
{ name: 'Book 3',
bestSelling: true,},
];

const bestSellingBooks = books.some((obj) => !obj.bestSelling);

console.log(bestSellingBooks ? false : true);

  • Related