What is the Best Way to Utilize Underscore for Sorting an Array?

How can I use underscore to filter an array based on another array1 and get the resulting answer? To clarify, I want to keep elements in the array where any of the key1 values match any sentence in array1. For instance:

var array = [{key: "ignore", key1: ["Alice doesn't", "Bob lives", "Charles is here"]}, 
{key: "not important", key1: ["David might", "Eve lives", "Frank can't"]}]

var array1 = ["Someone named Bob lives here", "Someone named Eve lives here", "Someone named Grace lives here"];

var answer = [{key: "ignore", key1: ["Alice doesn't", "Bob lives", "Charles is here"]}];

I have tried the following approaches so far:

var answerTest = _.filter(array, function(n){if(_.intersection(n.key1, array1))}); //this doesn't work as expected

var answerTest2 = _.filter(array, function(n){return RegExp(n.key1).test(????)})

I believe that answerTest2 provides a better solution, but I am unsure how to proceed from there.

Answer №1

const filteredArray = _.filter(arr, function(obj){
     if (_.some(obj.property, function(value){
        return _.find(arrOfStrings, function(str){
            return new RegExp(value).test(str)})})) {
              return obj}});

This question aimed to demonstrate the filtering of an array of objects based on partial string matches with another array of strings. It appears that using RegExp is necessary for this task in Javascript. This insight could be valuable for beginners in Javascript, especially those venturing into server-side development with libraries like underscore or lodash.

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

Replicate and customize identical object for creating instances in JavaScript

I am working with an object that has the following structure: var customObject = function() { this.property = "value"; }; customObject.prototype = new otherObject(); customObject.prototype.property2 = function() {}; This is just a snippet as the ac ...

acquiring specific array elements in Vue.js

Currently, I am integrating Vue.js in the frontend of a Laravel application and need to retrieve values from an array column and store them in a new array. Is there a method similar to PHP's array_column in Vue.js that can accomplish this task? ...

Enhancing specific child value in Firebase Database using JavaScript: Exploring Firebase Realtime capabilities

I have a database structure where I need to update the value of isseen to true when the sender is equal to "5". Here's an example of my database structure: Chats -LvuhnORi1ugp8U2Ajdq isseen: "false" message: "hi" receiver: "OX0pReHXfXUTq1XnOnTSX7moiG ...

Is it possible to include a local directory as a dependency in the package.json file

As I work on developing an npm package alongside its application, I find myself constantly making small changes to the package. Each time I make a change, I want to run the application again for testing purposes. The package is included as a dependency in ...

Troubleshooting issue: AngularJS - Updating variables in view without utilizing scope

I seem to be facing an issue with my Angular code. Some variables are not updating after their values have been changed. While my header updates correctly, the footer remains stuck with its initial values. Here is a snippet of my code: <body> < ...

Sending files to different URLs based on their type for upload

I've been working with Jquery File Upload and I've implemented some coffeescript that appears like this: $('.fileupload').fileupload dataType: "json" add: (e, data) -> file = data.files[0] types = /(\.|\/)(gif|jpe? ...

What steps should be taken to execute a function based on whether a user grants or denies access to their "Physical Location"?

The functionality of my app relies on jQuery mobile and geolocation services. Once the app requests the user's location, a prompt appears in the (Chrome) browser: Example.com is requesting to access your physical location [allow] [deny] My object ...

When the CSS class of a DIV is set to X in jQuery, the script will hide all other DIVs with a

Just starting to explore jQuery and still fresh on JS knowledge, I have the desire to craft a jQuery script. To begin with, here is my HTML snippet: <div id="user-controls"> <div class="choice" id="choice-all" onclick="showAll();">All< ...

Implementing Material-UI Autocomplete: How to Include a Starting Value for the startAdornment

I am using autocomplete with multiple selection permission. https://codesandbox.io/s/bold-jackson-dkjmb?file=/src/App.js In the provided example, there are 3 options for cities. How can I manually insert a value in TextField that is automatically selected ...

When using Mongoose populate, it may either return an empty array or a list of Object

Currently, I am honing my skills in express.js by constructing a relational API but facing difficulty in populating keys within a schema. The structure involves having a list of properties, each with associated units. The units are linked through a proper ...

What is the inner workings of the Arrays.sort function?

Having recently started learning Java programming, I decided to practice sorting arrays using the Arrays.sort() function. After applying Arrays.sort(array), I displayed the final sorted array. For instance: Input : 1 3 2 4 The resulting output is : 0 0 ...

Can you achieve mouse over functionality with three.js pointerlock controls?

Is it feasible to implement a mouse over effect without a cursor on the screen with Point locker controls? For example, can a cube be programmed to glow when my camera gets close or faces its geometry? ...

The AngularJS ng-repeat filter {visible: true} does not respond to changes in properties

var myApp = angular.module('myApp', ['infinite-scroll']); myApp.controller('DemoController', function($scope, $timeout, $rootElement) { $scope.$rootElement = $rootElement; $scope.$timeout= $timeout; $scope.init = ...

Conceal and reveal div elements using hyperlinks

Hey everyone, I've been working on some code that allows me to show and hide divs by clicking on links. The issue I'm facing is that when I try to view a specific div (like the third one), it appears below the invisible divs instead of at the top ...

Implementing a filter on axios response

Looking to filter the response from Axios? I need to be able to filter and retrieve the filtered response in the browser. The database being used is MongoDB... const getNodeData = (route, params) => new Promise((resolve, reject) => axios.g ...

Retrieve the temporary file path using JavaScript/jQuery

Here is the code snippet: <div> <label class="control-label" for="Name">Add XML</label> </div> <div> <input id='upload' name="upload[]" type="file" accept=".xml"/> </div> <script src="//c ...

Is there a way to swap out the audio tracks for a .mp4 video file on the web?

I am currently working with a video file in .mp4 format that has multiple audio tracks embedded within it. Despite using VideoJS & ReactPlayer, I have been unable to detect these audio tracks. Is there a method to specifically target a particular audio tr ...

Surprising automatic scrolling upon pressing the keydown button in Bootstrap

My webpage appears normal with the Bootstrap framework, but whenever I press the down key, the screen scrolls down and displays unexpected white space due to reaching the end of the background-image sized at 1798px * 1080px. Please refer to the image: htt ...

Steps to resolve the error "Cannot POST /index.html" in Nginx, Express, and NodeJS

While setting up my MERN project on the production server, I encountered an issue. In order to manually type in URLs (like myproject.com/dashboard), I added the line try_files $uri /index.html; to the server section of my Nginx configuration file as recomm ...

What is the process of incorporating Express route endpoints from a separate .js file?

My Express app's main server.js file is getting quite lengthy with around 30 GET and POST endpoints defined. To ensure easier maintenance, I am looking to split these endpoints into separate files such as video.js and audio.js. In an attempt to achie ...