Sort out information according to numerous user inputs

I am currently working on data filtering and struggling to extract text values from the tags property for comparison with the input array. How can I implement this in JavaScript?


let user_input =["Bananas", "Kiwi"]

const data= [
{
      id: 18,
      username: "james",
      tags: [ { id: 1, text: "Bananas" }, { id: 2, text: "Mangos" }]
    },
{
      id: 17,
      username: "anita",
      tags: [ { id: 3, text: "Bananas" }, { id:4 , text: "Oranges" }, { id:5 , text: "Strawberries" } ]
    },
{
      id: 16,
      username: "david",
      tags: [ { id: 2, text: "Mangos" }]
    },
{
      id: 15,
      username: "nicole",
      tags: [ { id: 6, text: "Kiwi" }]
    },
]

The expected output should be

[{id: 18 ...}, {id:17 ...}, {id:15 ...}]

Answer №1

To determine if the text values in the `user_input` array are included in the `tags` array of each object, you can utilize a combination of the `filter()`, `some()`, and `includes()` methods.

const data = [{ id: 18, username: "james", tags: [{ id: 1, text: "Bananas" }, { id: 2, text: "Mangos" }] }, { id: 17, username: "anita", tags: [{ id: 3, text: "Bananas" }, { id: 4, text: "Oranges" }, { id: 5, text: "Strawberries" }] }, { id: 16, username: "david", tags: [{ id: 2, text: "Mangos" }] }, { id: 15, username: "nicole", tags: [{ id: 6, text: "Kiwi" }] },];

const user_input = ["Bananas", "Kiwi"];

const result = data.filter(({ tags }) =>
  tags.some(({ text }) => user_input.includes(text)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


If you wish to only retrieve objects that contain all the tags in the `user_input` array, you can achieve this by using the `every()`, `map()`, and `includes()` functions as detailed below.

const data = [
  { id: 18, username: "james", tags: [{ id: 1, text: "Bananas" }, { id: 2, text: "Mangos" }] },
  { id: 17, username: "anita", tags: [{ id: 3, text: "Bananas" }, { id: 4, text: "Oranges" }, { id: 5, text: "Strawberries" }] },
  { id: 16, username: "david", tags: [{ id: 2, text: "Mangos" }] },
  {
    id: 15, username: "nicole",
    tags: [
      { id: 6, text: "Kiwi" },
      { id: 6, text: "Bananas" }]
  }
];

const user_input = ["Bananas", "Kiwi"];

const result = data.filter(({ tags }) =>
  user_input.every(tag =>
    tags
      .map(({ text }) => text)
      .includes(tag)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Parsing JSON within an HTML document

It seems like what I'm attempting to do should be straightforward, but for some reason, I can't seem to get it to work? Let's say I have the following JSON file named jsonFile.json: { "level1": "elemet1", "level2": "element2", ...

What is your approach to converting this jQuery code to ES6 syntax?

The concept involves gathering all the links and corresponding IDs, and hiding inactive content. When a link is clicked, the associated content should be displayed. The Structure <div class="navbar"> <nav> <ul class="navTabs"> ...

Passing data into Angular 4 components: a step-by-step guide

I'm facing a dilemma, I'm attempting to transfer data from one component to another in Angular 4, the data seems to be transferred successfully but it does not display, let me show you an example of the code: board.component.ts: import { Compon ...

Creating a Jasmine test for the event.target.click can be accomplished by defining a spec that

I need help creating a Jasmine test spec for the following method in my component. Here is my Component Method methodName(event): void { event.preventDefault(); event.target.click(); } I have started writing a test but don't fully cover event. ...

Is it advisable to incorporate await within Promise.all?

Currently, I am developing express middleware to conduct two asynchronous calls to the database in order to verify whether a username or email is already being used. The functions return promises without a catch block as I aim to keep the database logic se ...

Can a TypeScript-typed wrapper for localStorage be created to handle mapped return values effectively?

Is it feasible to create a TypeScript wrapper for localStorage with a schema that outlines all the possible values stored in localStorage? Specifically, I am struggling to define the return type so that it corresponds to the appropriate type specified in t ...

Exploring the world of third-party widgets: Comparing Angular, jQuery, and traditional JavaScript

I have a plan to develop a simple embeddable widget similar to Google ads or Facebook like box. Users will be able to easily add the widget to their website and I will extract some parameters to fetch data from my servers. Previously, I relied on jQuery f ...

Guide on importing table information into an array using jQuery

I am facing an issue where I want to extract values from a dynamically generated table and then send those values in an AJAX call. The problem is that even though I am able to increase the number of rows in the table dynamically, when I try to capture the ...

Exploring a Java application

Currently, I am attempting to comprehend a Java program. This particular line of code is what I am focusing on: String[] words = line.split(" "); Will this code also separate the ';' from the variable name appearing before it? For instance: ...

Iterate through an array to extract specific objects and exclude them from another array

Within my code, I have an array named allItems that stores objects. allItems = [ { id: 1, name: 'item1' }, { id: 2, name: 'item2' }, { id: 3, name: 'item3' } ] I am seeking a way to filter out the objects from th ...

What could be causing my JavaScript code to malfunction, even though it appears to be coded correctly?

// JavaScript Document "use strict"; $(window).scroll(function(){ if($(window).scroll() > 100){ $("#scrollTop").fadeIn(); } }); $(window).scroll(function(){ if($(window).scroll() < 100){ $("#scrollTop").fadeOut(); } }); $(document).ready(function() ...

Toggle Jquery menu with a click of a button

I need help with creating a menu for a forum that opens on click and closes on click. Here is the code I have so far: /*Custom BBPress admin links menu*/ function wpmudev_bbp_admin_links_in_menu($retval, $r, $args) { if ( is_user_logged_in() ) { $me ...

Crop the contents of an array between two specified characters

Looking to extract individual values from an array like this: "Names": [ "Name[name]", "Result[Type]", "Validation[Option]", "Status[Pointer]" ] The desired output should be: "Names": [ "name", "Type", "Option", ...

Is it possible to have setTimeOut() executed after the page has been redirected?

Why is it not possible to duplicate: The question was not addressed in the previous post. I have a link for deletion, which, when clicked, triggers a popup with a button. Upon clicking that button, the page inside the popup redirects to a new internal pag ...

What is the best way to attach every object to its corresponding group of elements?

var clubbingLocations = $('#clubbing-locations'); $.getJSON("/js/location.json", function(data) { //loading the json file for (var i = 1; i <= data.locations.length; i++){ // iterating through the locations in the json file clubb ...

Updating dropdown menu with JSON data through Jquery ajax

Despite the numerous inquiries on this subject, I am still unsure about what steps to take. I have designed an HTML form named "CuisineForm", where once the user selects a cuisine type, AJAX sends the form data to the server. The AJAX call is functioning ...

JavaScript list in Google Docs

I am a beginner in the world of the Google Docs API and I am interested in retrieving a list of all documents that are not spreadsheets using the Google Docs API. I have found an API that allows me to access a specific document when I provide its documentI ...

Create an array within a class and then access it outside of the class

To address this issue, I have designed a method to create an array containing ID posts within a function, and then access it outside the class. Here is my code: <?php class cat_widget extends WP_Widget { private $newHomePost = array(); function wi ...

After the rendering of the HTML, the value of the jQuery input does not change

Here we have a function that loads HTML onto the form class in a file. The quest[q] locates the appropriate HTML template to load from an array of templates. The HTML being loaded contains an input with an id of "p". I am attempting to set the value of th ...

Utilize A-frame image resources within JavaScript code

Currently, I am utilizing an image as a texture in multiple instances. Once through the material component and another time within a custom component where I am using THREE.TextureLoader(), resulting in the application loading the image two times. I believ ...