Here's a method of sorting through an array of objects and displaying all objects that include a specific keyword in one of their values

I am currently working on a project involving an array of book objects. My task is to display a list of all books that have either "companies" or "people" in their title using console.log.

const books = [{
    title: 'How to win friends and influence people',
    authors: ['Dale Carnegie'],
    publisher: 'Pocket Books',
    year: '1936'
  }, {
    title: 'Management: tasks, responsibilities, practices',
    authors: ['Peter F. Drucker'],
    publisher: 'Harper Business',
    year: '1985'
  }, {
    title: 'Strength finder 2.0',
    authors: ['Tom Rath'],
    publisher: 'Gallup Press',
    year: '2007'
  }, {
    title: 'In search of excellence: Lessons from America\'s best-run companies',
    authors: ['Thomas Peters', ' Robert H. Waterman'],
    publisher: 'Harper Collins',
    year: '1982'
  }, {
    title: 'Built to last: Successful habits of visionary companies',
    authors: ['James C. Collins', 'Jerry I. Porras'],
    publisher: 'Harper Collins',
    year: '1994'
  }, {
    title: 'Reengineering the corporation: A manifesto for business revolution',
    authors: ['Michael Hammer', 'James A. Champy'],
    publisher: 'Harper Collins',
    year: '1993'
  }, {
    title: 'Competitive advantage: Creating and sustaining superior performance',
    authors: ['Michael E. Porter'],
    publisher: 'Free Press',
    year: '1998'
  }, {
    title: 'Crossing the chasm: Marketing and selling technology products to mainstream customers',
    authors: ['Geoffrey A. Moore', 'Regis McKenna'],
    publisher: 'Pocket Books',
    year: '1936'
  }, {
    title: '7 habits of highly effective people: Powerful lessons in personal change',
    authors: ['Stephen R. Covey'],
    publisher: 'Simon and Shuster',
    year: '1990'
  }, {
    title: 'The Six Sigma Way',
    authors: ['Peter S. Pande et al', 'Robert P. Neuman', 'Roland R. Cavanagh'],
    publisher: 'McGraw Hill',
    year: '2000'
  }, {
    title: 'The innovator\'s dilemma: When new technologies cause great firms to fail',
    authors: ['Clayton M. Christensen'],
    publisher: 'Harvard Business School Press',
    year: '1997'
  }, {
    title: 'The Essential Drucker',
    authors: ['Peter F. Drucker'],
    publisher: 'Harper Business',
    year: '2001'
  }];

My current approach involves using filter() and includes() methods as shown below. However, the code is only returning books with the keyword "people".

let keyWord = books.filter (bookTitle => bookTitle.title.includes('people'||'companies'));
console.log(keyWord);

Answer №1

Avoid using the OR operator within include() in order to write the logic externally.

books.filter(book => book.title.includes('companies') || book.title.includes('people'))

If you require a case-insensitive match:

books.filter(book => {
    const titleLower = book.title.toLowerCase()
    return titleLower.includes('companies') || titleLower.includes('people')
  })

Answer №2

If you're looking to achieve a specific outcome, I recommend utilizing Array.filter() in conjunction with Array.some().

The approach involves creating an array of keywords and then filtering out items based on whether they match some of these keywords.

const books = [{ title: 'How to win friends and influence people', authors: ['Dale Carnegie'], publisher: 'Pocket Books', year: '1936' }, { title: 'Management: tasks, responsibilities, practices', authors: ['Peter F. Drucker'], publisher: 'Harper Business', year: '1985' }, { title: 'Strength finder 2.0', authors: ['Tom Rath'], publisher: 'Gallup Press', year: '2007' }, { title: 'In search of excellence: Lessons from America\'s best-run companies', authors: ['Thomas Peters', ' Robert H. Waterman'], publisher: 'Harper Collins', year: '1982' }, { title: 'Built to last: Successful habits of visionary companies', authors: ['James C. Collins', 'Jerry I. Porras'], publisher: 'Harper Collins', year: '1994' }, { title: 'Reengineering the corporation: A manifesto for business revolution', authors: ['Michael Hammer', 'James A. Champy'], publisher: 'Harper Collins', year: '1993' }, { title: 'Competitive advantage: Creating and sustaining superior performance', authors: ['Michael E. Porter'], publisher: 'Free Press', year: '1998' }, { title: 'Crossing the chasm: Marketing and selling technology products to mainstream customers', authors: ['Geoffrey A. Moore', 'Regis McKenna'], publisher: 'Pocket Books', year: '1936' }, { title: '7 habits of highly effective people: Powerful lessons in personal change', authors: ['Stephen R. Covey'], publisher: 'Simon and Shuster', year: '1990' }, { title: 'The Six Sigma Way', authors: ['Peter S. Pande et al', 'Robert P. Neuman', 'Roland R. Cavanagh'], publisher: 'McGraw Hill', year: '2000' }, { title: 'The innovator\'s dilemma: When new technologies cause great firms to fail', authors: ['Clayton M. Christensen'], publisher: 'Harvard Business School Press', year: '1997' }, { title: 'The Essential Drucker', authors: ['Peter F. Drucker'], publisher: 'Harper Business', year: '2001' }];

const keyWords = ['people', 'companies'];

function findMatchingTitles(books, keyWords) { 
    return books.filter(({title}) => { 
        return keyWords.some(keyword => title.includes(keyword));
    })
}

console.log('Matching titles:');
const result = findMatchingTitles(books, ['people', 'companies']);
result.forEach(book => console.log(book.title));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

If you're looking to filter through a list of items based on specific criteria, you can make use of regular expressions. For example:

const peopleRegex = /people/i
const companiesRegex = /companies/i

const filteredItems = items.filter(item => peopleRegex.test(item.title) || companiesRegex.test(item.title))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Streamlining data entry with an uncomplicated HTML form input that accepts multiple values from a

As I understand it, a barcode scanner functions as nothing more than a keyboard that transmits keycode 13 after each scan. My task is straightforward: I have a basic form with only one input field and I want the ability to scan numerous barcodes and then c ...

Postponing the execution of a controller until all JSON files have been fully loaded

I am currently trying to grasp the concepts of AngularJS, so my question might not be perfect. Is it feasible to delay the execution of a controller until the json files are fully loaded in a separate function? Below is the controller code: app ...

javascript show and hide navigation bar

I am currently working on a HTML menu that includes a button to open it and an unordered list : <nav class="menu"> <button> <h1>Menu</h1> </button> <ul class="mylist" ...

Receive Real-Time Notifications -> Update Title Using an Array Retrieved from a JSON File

I've been working on updating a live chart every 5 seconds with new data from the database. While I could easily update the information, I encountered a problem when trying to set a path within the chart options for tooltips callbacks afterTitle. Spec ...

Imitate the experience of using aframe view manipulation

Is there a method to imitate user input in my Webvr application? Could I reproduce look controls in Aframe? <a-entity listener position="0 0 0" id="camera" camera="userHeight: 1.6" look-controls> ...

Converting Node JS request to an API into React Fetch syntax

I have encountered a problem while developing an app in React-Native that connects with the Hubspot API. Initially, I tried to make the request using the Node JS request module, but it didn't work well with React Native when Expo was involved. Now, I ...

Issue with Next.js's notFound() function not properly setting the 404 HTTP Header

Our decision to use Nextjs was primarily driven by the need for SSR and SEO optimization. We rely on an external REST API to fetch data on the front end, but we face challenges when trying to pre-render certain pages and display a proper 404 Not Found head ...

The toast feature in Bootstrap 5 seems to be malfunctioning as it does not display properly despite the absence of any

Why isn't the Toast displaying in the code snippet below? I'm using bootstrap 5. I'm puzzled because there are no errors in the developer's tools. Any assistance would be greatly appreciated. <!DOCTYPE html> <html lang="en"& ...

Node.js has no trouble loading HTML files, however, it seems to encounter issues when trying to

Having a bit of trouble with my JavaScript skills as I try to load my index.html file (seems like it should be the 5th easiest thing to do in JavaScript). Let me get straight to the point; when I manually open my index.html, it loads perfectly WITH the CS ...

Selenium fails to detect elements that are easily located by the browser using the aba elements, as well as through the use of JavaScript in the console

Looking to automate actions on the bet365 casino platform, but facing challenges with bot blocking mechanisms. Visit: Struggling to interact with elements within the "app-container" div using Selenium, however able to access them via JavaScript in the br ...

What is the Best Way to Retain My Firefox Settings While Handling a JavaScript Alert?

I'm encountering an issue when trying to download a file by clicking on a link. I have set my Firefox preferences to save the file in a specific location. However, upon clicking on this particular link, a popup appears that I must accept before the do ...

PHP cannot be utilized within the script tag

I'm currently using JavaScript to display an error message If a user inputs incorrect information and I add the following code: <?php $_POST["usernamereg"] ?> = usernamereg; the alert function stops working. However, if I remove this code, t ...

How to adjust cell alignment in Handsontable

Handsontable showcases cell alignment options in the align cell demo: Horizontal Left Center Right Justify Vertical Top Middle Bottom Displayed below is a screenshot: To retrieve data, utilize the following code snippet: $('#table-wrapper&ap ...

Acquire Formik Validation for the Current Year and Beyond

How can I ensure that the input in Formik is restricted to the currentYear and later years only? const currentYear = new Date().getFullYear(); expiryYear: yup .string() .required('Please select an expiry year') .min(4, `Year format must be grea ...

What is the best way to dynamically search and retrieve data from a JSON object in Angular?

I am facing a challenge with my Angular (v. 1.6.3) app where I have fetched a JSON object containing stock price data. The structure of the JSON object only allows querying using brackets, with each key being a string that may include spaces, parentheses, ...

Make sure to switch up the font color with each new use of the "append" function

Currently, on my page, I am using the append function to add a new line of text (".newText") every 5 seconds. This is my current implementation: var fontColors var randomColor $(function(){ fontColors = ['red','orange','yello ...

Adding a version number to the splash screen in Cordova: A step-by-step guide

After successfully integrating the Cordova Splashscreen plugin into my Ionic project, everything is running smoothly. However, I am now looking to dynamically add a version number to the splash screen without manually editing the Splash Screen PNG file e ...

Why is the oninput function in JavaScript not functioning properly?

After following a practical video tutorial step by step, I tried to implement the code provided (in HTML and JS) but nothing seems to be working! The code snippet from the tutorial includes: var $count = document.getElementById("count"), $textarea = ...

Customizing the default button in Ant Design Popconfirm to display "Cancel" instead

When the Ant Design Popconfirm modal is opened, the Confirm ("Yes") button is already preselected. https://i.stack.imgur.com/bs7W7.png The code for the modal is as follows: import { Popconfirm, message } from 'antd'; function confirm(e) { c ...

Dealing with prompt boxes in Robot Framework: A Guide

Currently, I am utilizing the Robot Framework in conjunction with Selenium2Library for automating tests on websites. During one particular scenario, a prompt box appeared (similar to an alert but containing an input field). The challenge is that Robot Fram ...