Narrow down an array in Javascript based on several criteria

I am trying to implement a search functionality that filters an array and displays only the matching results.

let songs = [
   {name: 'Let It Be', artist: 'The Beatles},
   {name: 'Lady Madonna', artist: 'The Beatles },
   {name: 'Mama Mia', artist: 'The Beatles}
];

In this example, the filtering is done based on the song name.

let value = 'name';
let q = 'Let it be' // user input entered in the search box;

let songFilter = songs.filter(function(song) {
   return song[value].toString().toLowerCase().indexOf(q) != -1; // returns true or false
});

Currently, entering Let It Be in the search box will only display 'Let It Be'. But I want to be able to filter by multiple songs. For instance, entering Let It Be, Lady Madonna should return both matching songs.

I have tried various methods but haven't been successful in achieving this. I also have access to lodash which might help simplify the solution.

Answer №1

const filteredSongs = songs.filter(function(song) {
    ['let it be', 'lady madonna'].includes(song[value].toString().toLowerCase())
});

Answer №2

To efficiently keep track of input entries, utilize a Set to store the keys after using the split method. This approach enables you to quickly determine if there is a match or not. The Set is then passed as the context to the filter function, allowing it to be referenced with this:

let songs = [
   {name: 'Let It Be', artist: 'The Beatles' },
   {name: 'Lady Madonna', artist: 'The Beatles' },
   {name: 'Mama Mia', artist: 'The Beatles' }
];

function find(byKey, valueCsv) {
    return songs.filter(function(song) {
       return this.has(song[byKey].toLowerCase())
    }, new Set(valueCsv.trim().toLowerCase().split(/\s*,\s*/)));
}

songInput.addEventListener('input', function() {
    matches.textContent = JSON.stringify(find('name', songInput.value), null, 2);
});
Type in the name of the song(s):<input id="songInput" style="width:100%">
<pre id="matches"></pre>

Answer №3

implementing Array#filter along with Array#find

let tracks = [
   {title: 'Bohemian Rhapsody', band: 'Queen'},
   {title: 'Sweet Child O\' Mine', band: 'Guns N\' Roses' },
   {title: 'Purple Haze', band: 'Jimi Hendrix'}
];
let key = 'title';
let input = 'Bohemian Rhapsody,Sweet Child O\' Mine'; // user input from form;
let splitInput = input.split(',').map(item=>item.toLowerCase());

let trackFilter = tracks.filter(t=>splitInput.find(item=>t[key].toLowerCase().indexOf(item) > -1 ) !== undefined );

console.log(trackFilter);

Answer №4

Reiterating my point made in the previous comment:

let songs = [
   {name: 'Let It Be', artist: 'The Beatles'},
   {name: 'Lady Madonna', artist: 'The Beatles'},
   {name: 'Mama Mia', artist: 'The Beatles'}
];

let value = 'name';
let q = 'Let it be, Lady madonna';

// To begin with: divide the q value into individual songs (and convert them to lowercase)
let qSongs = q.split(', ').map(e => e.toLowerCase());

// Next: filter out songs that match the ones in the above result array (qSongs)
// for each song in the songs array
let songFilter = songs.filter(song => 
  // check if there is any qsong in the qSongs array such that the value of song matches qsong
  qSongs.some(qsong => 
    song[value].toLowerCase().indexOf(qsong) != -1
  )
);
    
console.log(songFilter);

Answer №5

let songs = [
  { name: 'Let It Be', artist: 'The Beatles' },
  { name: 'Lady Madonna', artist: 'The Beatles' },
  { name: 'Mama Mia', artist: 'The Beatles' }
];

let value = 'name';
let q = 'Let it be, Lady madonna';

let songFilter = _.filter(songs, (song) => {
  let regex = new RegExp(q.replace(/\s*,\s*/g, '|'), 'gi');
  return regex.test(song[value]);
});

console.log(songFilter);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

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

Tips for utilizing a dot-separated string as the object path for the v-model directive in Vue

I am working with a data record record: { address: { city: "" } } There is an array of objects that describe fields fields: [ { name: "address.city" ... } ] My objective is to generate a form dynamically <b- ...

modifying the click state using a variable in jquery

Something feels off about my approach to this task. I currently have a series of hyperlinks, and when they are clicked, they go through a short sequence before changing states. When clicked again, they revert to their original state. var favourites = fun ...

Discover the ultimate guide to creating an interactive website using solely JavaScript, without relying on any server-side

I'm facing a challenge: I have a desire to create a website that is mainly static but also includes some dynamic components, such as a small news blog. Unfortunately, my web server only supports static files and operates as a public dropbox directory. ...

Array automatically updates its values

.... import * as XLSX from 'xlsx'; ... I am currently parsing a .xlsx file in an Ionic 4 application. showData() { let fileReader = new FileReader(); fileReader.onloadend = (e) => { this.arrayBuffer = fileReader.result; let data ...

Looking to find a specific array value in MongoDB and add to it?

{ "_id": "100", "menu": [ { "type": "1", "isenabled": true, "items": [ { "key": "ac ...

Node.js: Exploring the Differences Between Synchronous and Asynchronous Code

Currently, my team is delving into the world of node for an internal project and to gain a deeper understanding of how to utilize this technology effectively. As individuals without a specific asynchronous background, we are facing some challenges with th ...

Sending out a command does not equate to establishing Redux with an outcome

I've been grappling with this issue for the past 18 hours and I'm at a loss to figure out what's causing the problem. My redux setup is working smoothly as it dispatches actions and receives state correctly for other components. However, in ...

"JavaScript code for creating a dynamic switching effect in HTML

I currently have 4 divs on my webpage that can be hidden or shown using JavaScript when clicking the menu at the top of the page. Here is my current script: <script type="text/javascript"> function showHide(d) { var onediv = document.get ...

Add the schema-form to the app.module for importing

I've been attempting to incorporate the angular-schema-form into my angular project, but I'm facing issues with importing it in my app.module.ts file. Here is my current configuration: app.module.ts import { BrowserModule } from '@angular/ ...

Top tips for accessing a file that has been uploaded using the $http service and the HTML5

I've encountered an issue while trying to upload an image within an Angular application. Here's the code snippet in question: var f = document.getElementById('product-image').files[0], r = new FileReader(); r.onload ...

How can jQuery grep be used with dual arrays?

Could it be a problem with my syntax, or am I completely off track with my approach here? I'm working with two arrays that store attributes selected by the user. I'm then attempting to filter a JSON file using $.grep() to find pillows that match ...

How to Exclude ress.css in Vuetify.js

How can I prevent ress.css from conflicting with Bootstrap and my custom styles in Vuetify? I attempted to remove it from the Vuetify directory within node_modules, but that did not resolve the issue. ...

Can you explain the distinction between key and id in a React component?

I have included this code snippet in the parent component. <RefreshSelect isMulti cacheOptions id='a' key = 'a' components={makeAnimated()} options={th ...

The browser window is converting the date automatically

I am currently facing an issue with date printing on the frontend of a website I'm developing. The date is fetched from a MySql database using Node.js (mysql module) and stored in the database as a MySql DATETIME format. The view engine in use is Hand ...

Duplicating a file within the Flask app directory while understanding its designated web route

After creating a web path of a file, I utilized the following code snippet: URL.createObjectURL(event.target.files[0]); Following an ajax call, I sent this link to Python (Flask). I am now interested in learning how to utilize this link to duplicate the ...

Reloading the table columns in a JSP page with a click of the refresh button on every row using AJAX and JavaScript

Hey there! I have a JSP page with a table where data is displayed by iterating through a list from the action class. Each row in the table has a refresh button at row level. Here is a snippet of the JSP: <script type="text/javascript"> functi ...

Is there a way to conceal the parent div when all of its child divs are hidden?

I have a series of dynamically created divs set up like this: <div class='parent'> <div class='child'></div> <div class='child'></div> <div class='child'></div> < ...

Is it secure to send the one-time authorization code for Google+ Hybrid server-side flow over HTTP?

Hello, I have decided to transition from using Google's Client-side flow to the Hybrid server-side flow. Previously, I would send the client an access_token and then transfer it to the server to verify the user before logging them in or creating a new ...

The Apexchart-reactjs library is currently unable to display Arabic language in the labels

Currently, I am utilizing the Apexchart-reactjs library to create a line chart. The issue at hand is that I require the y labels to be displayed in Arabic language, but it seems like the library does not support this feature. Despite reaching out to the de ...

Sorting through alike numbers and separating them into distinct arrays

I have a text file that is structured like this: 63001230 3 10 63001234 8 3 63000176 8 6 63001432 - 0 The first 8-digit number has already been stored. Now, I need to store the second column (3 8 8 -) in one array and the third column (10 3 6 0) in anoth ...