Checking in Underscore.js if the whole array exists inside another array

Currently learning about Underscore.js. I am attempting to filter an array of objects by checking if all items in a tags array exist in the object's tags.

I am using Underscore's filter and every methods, like so:

/* data set */
var colors = [
  {
    "id": "001",
    "tags": ["color_family_white", "tone_warm", "room_study"]
  }, 
  {
    "id": "002",
    "tags": ["color_family_white", "tone_neutral"]
  },
  {
    "id": "003",
    "tags": ["color_family_red", "tone_bright", "room_kitchen"]
  }
];

/* filtering example for white */
var tags = ["color_family_white", "room_study"];

var results = _.filter(colors, function (color) {
    return _.every(tags, function() { /* ??? what to do here */} );
});

All tags must be present on color.tags, returning only color 001 in this case.

This demonstrates my goal: http://jsfiddle.net/tsargent/EtuS7/5/

Answer №1

One possible solution is to utilize the indexOf method:

var results = _.filter(colors, function (color) {
    return _.every(tags, function(tag) { return _.indexOf(color.tags, tag) > -1; } );
});

Alternatively, you can use the native indexOf function:

var results = _.filter(colors, function (color) {
    return _.every(tags, function(tag) { return color.tags.indexOf(tag) > -1; } );
});

For a more concise approach, consider employing the difference function:

var results = _.filter(colors, function (color) {
    return _.difference(tags, color.tags).length === 0;
});

View Demo

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

Exploring Rails integration with FullCalendar: Retrieving data from the database using varying column titles

Currently utilizing Rails 4.0 in conjunction with FullCalendar, I am encountering an issue where some fields in my database do not align perfectly with the defaults of FullCalendar. For instance: My columns FullCalendar's Na ...

Show an object in a collection just once if it shares the same identification, while also showcasing all other attributes

In order to achieve my goal, I aim to showcase the fromUsers individually without any duplicates. For example, if there are 2 messages from the same person named John (with the same fromUserId), I only want John's name to be displayed once. Clicking o ...

Issue arising due to incorrect array index placement following the axios request

I am currently utilizing vue js and axios for my project. Here is the challenge I am facing: Typically, my "outlines" array contains anywhere from 3 to 9 entries. I want to send an axios request (runSecondFunction()) for each entry, but execute only one ...

`methods that exhibit peculiar behaviors`

My routes are set up with the get method. app.get("/info/teachers", controller1); app.get("/info/teachers/:teacherid", controller2); app.get("/info/students", controller3); app.get("/info/students/:studentid", contr ...

When attempting to start the server in Node.js, an error is thrown stating that the issue needs to be resolved with a middleware function

I am experiencing an issue when attempting to start the server after creating a route and using it in the app.js file. I need assistance in resolving this error as I have been stuck on it for hours. I have made several edits but none seem to work. Here is ...

Activate the Bootstrap modal when the React site fully loads

Is there a way to display a modal with information as soon as a page loads in React? I attempted using the standard method: $(window).on('load',function(){ $('#myModal').modal('show'); }); However, it seems ineffective p ...

Having trouble clicking on an element in Selenium Webdriver with Python? It seems like the property 'click' is returning null

Encountering an error when attempting to execute this command: driver.find_element_by_link_text("Confirm").click() selenium.common.exceptions.WebDriverException: Message: unknown error: Element <a href="javascript:void(0);" class="c-button u-fontSize1 ...

Is there a way to efficiently navigate a local JSON file using React JS?

What is the best way to extract data from a JSON file and utilize it within my code? I attempted importing the file and logging it in the console, but all I get is Object {}: import jsonData from "./file.json"; console.log(jsonData); This is the content ...

Exploring Source Map Explorer in Next.js: A Beginner's Guide

Looking for assistance in analyzing the Next.js build using source-map-explorer. Can anyone provide guidance on the script? For React (CRA), the script I use is: "build:analyze": "npm run build && source-map-explorer 'build/sta ...

Bootstrap Carousel with descriptions in a separate container without any display or hiding transitions

I have created a slider using Bootstrap and some JavaScript code that I modified from various sources. Everything is working well, but I want to remove the transition or animation that occurs when the caption changes. Currently, the captions seem to slide ...

Exploring a JavaScript function that triggers another function to create a new object - Utilizing Sinon and Mocha for testing purposes

I am currently working on a nodejs application where I need to write a test for a function that invokes another function to create a new object, and then calls a method of that object. Below is the code in service.js that I am trying to test; // servic ...

Inserting a custom text box underneath the Anything Slider

I am currently incorporating the Anything Slider into a website project. The main purpose of the slider is to showcase videos, but I would like to include a description text box beneath it that dynamically changes based on the selected tab. This snippet de ...

Is there a way to incorporate @Html.ValidationMessageFor into every element within a collection?

Is there a way to include @Html.ValidationMessageFor() for each item in a collection? Let's take an example, public class FooVm { // some property public ICollection<BarVm> Bars { get; set; } } public class BarVm { // some property [Ra ...

The eBay API is providing users with small thumbnail images with low resolution

Adding &outputSelector=GalleryInfo to the URL was supposed to give me a higher resolution thumbnail, but it doesn't seem to be working. I'm still new to JSON and the tutorial I'm following isn't very clear on the exact syntax needed ...

What are some ways to create a flashing effect for text in HTML and JavaScript?

Although flashing text is typically prohibited in many places, my client has requested it for a project. I need to create one line of text that flashes using HTML and JavaScript. The text should appear and disappear within seconds, repeating this cycle. I ...

Looking to set an object value as optional in JavaScript?

Hello, I am currently in the process of developing a web application using ReactJS with Auth0 for user authentication. In order to update user information on my backend, I am utilizing state to store the necessary data. My challenge lies in allowing eith ...

What steps can I take to improve the functionality of the slide navigation feature

I am currently working on implementing a sliding menu feature. The menu can slide open smoothly, however, I am encountering an issue when trying to close it by clicking on the 'x' button. let openNav = document.querySelector(".slideOpen"); ...

Using ngrx to automatically update data upon subscription

Background The technology stack I am using for my application includes Angular 4.x, ngrx 4.x, and rxjs 5.4.x. Data is retrieved from a websocket as well as a RESTful API in order to share it between multiple components through ngrx. Currently, data is ref ...

Utilize jQuery and JSP (or PHP) to showcase detailed information about a specific item when a user clicks on it within an HTML page

For my upcoming college project, I am tasked with developing a movie library. The main page of the library will feature various movie posters. Upon clicking on a poster, users will be directed to a dedicated page displaying detailed information about the ...

What is the best way to display table rows for a specified date range?

I am working with a table and need to display only the rows that fall between two specific dates. <table id ="Table"> <thead> <tr> <th>Date</th> <th>Name</th> <th>Desc</th> </tr> </thead> ...