Filtering data at different levels in Javascript/Javascript programming language

Consider this array:

var selection = ["14-3","19-5", "23-5", "40-8", "41-8"];

We now have two separate arrays: Array1 includes the first part of each value (before hyphens) in the original array, such as 19, 23, etc. Array2 includes the second parts - 5, 8, etc.

Array1 = ["23", "40"]
Array2 = ["5", "8"]

The goal is to filter out certain elements from the selection array based on the following criteria:

  • Exclude any items where none of the values match those in Array2
  • For items where there is a match with any value in Array2, only include those that also match the corresponding value in Array1

In this scenario, the resulting filtered array would look like this:

filteredSelection = ["14-3", "23-5", "40-8"]

While filtering an array by another using .filter() is straightforward, this specific case presents a challenge. Any assistance would be greatly appreciated.

Answer №1

To filter out specific values from the array, exclude elements from array2 and include elements from array1.

var selection = ["14-3","19-5", "23-5", "40-8", "41-8"],
    array1 = ["23", "40"],
    array2 = ["5", "8"],
    result = selection.filter(s => {
        const [l, r] = s.split('-');
        return !array2.includes(r) || array1.includes(l);
    });

console.log(result);

Answer №2

Give this a shot:

const selection = ["14-3","19-5", "23-5", "40-8", "41-8"];
const Array1 = ["23", "40"];
const Array2 = ["5", "8"];

const obj1 = Array1.reduce((acc, curr) => ({...acc, [curr]: 1}), {});
const obj2 = Array2.reduce((acc, curr) => ({...acc, [curr]: 1}), {});

const res = selection.filter(item => {
  const [left, right] = item.split('-');
  return obj1[left] || obj2[right] === undefined;
});

console.log(res);

Transformed Array1 and Array2 into objects for efficiency purposes. It is recommended to initialize Array1 and Array2 as objects from the start.

Answer №3

Using the filter method can be a powerful tool if utilized correctly:

const filteredItems = items.filter(item => {
  const [start, end] = item.split('-');
  return !arr2.includes(end) || arr1.includes(start);
});

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

Ways in which the user can modify the city name within this inquiry

I am just beginning to learn JavaScript and I am struggling to figure out how to allow the user to change the city name in this request. Currently, it works when I manually input the city name in the code (e.g., askWeather.open("GET", "url.../london")), bu ...

What sets apart `Object.merge(...)` from `Object.append(...)` in MooTools?

This question may seem simple at first glance, but upon further inspection, the MooTools documentation for the 'append' and 'merge' methods appears to be identical. Here is the code snippet provided in the documentation: var firstObj ...

When attempting to install an npm package from a local directory, I encountered a 404 Not Found error, despite the package existing in the node_modules directory

After installing an npm package from a local directory, I noticed that the package was successfully installed and is located in the node_modules directory. However, upon trying to access the package, I encountered the following error: 404 not found I a ...

Creating a ListView in React Native and utilizing the CloneWithRow method with an object instead of an

When retrieving data from a webservice, I am able to work with JSON arrays without any issues. WebServiceHandler.get('http:/api.local/stock',{},{) .then((val)=>{ this.setState({ dataSource: this.state.dataSou ...

Sorting tables with jQuery UI sortable() and rowspan功能

Can jQuery UI's sortable() be configured to sort rows based on their "containing" element only? I have a table with rowspanned cells that should only be sorted within their respective spanned columns. var $sortable = $('.nested-sortable tbody&ap ...

Sorting an array based on shortest distance in Javascript - A step-by-step guide

I need to organize an array so that each element is in the closest proximity to its previous location. The array looks like this: locations=[{"loc1",lat,long},{"loc2",lat,long},{"loc3",lat,long},{"loc4",lat,long},{"loc5",lat,long}] Here's the funct ...

The changes made to $scope in AngularJS are not being displayed in the view

The View Section <div class="col-sm-8" data-ng-init="init_enable_disable()"> <select class="form-control" style="margin-top: 5px;" data-ng-model="schedule.scheduleType" data-ng-change="enable_disableDiv(schedule.scheduleType);"> ...

Maximizing the efficiency of Java Script code

I am struggling with optimizing this JavaScript code that adds and removes classes based on the presence of a specific class in the next rows of a table. Can anyone provide some guidance on how to make this code more efficient? $(".showTR").click(functi ...

No results returned by Mongoose/MongoDB GeoJSON query

I have a Schema (Tour) which includes a GeoJSON Point type property called location. location: { type: { type: String, enum: ['Point'], required: true }, coordinates: { type: [Number], required: true ...

What is the reason behind the restriction on using capital letters in React project names?

When attempting to create a new project "newRecipeApp" in React, I encountered the following message: npx: installed 91 in 29.359s Could not create a project called "newRecipeApp" because of npm naming restrictions: * name can no longer contain capital ...

Should I generate an array or pull data directly from the database?

Hey there, I've got this JavaScript app and could really use some input or tips. Here's the idea: Users log in to try and defeat a 'boss', with each player working together in the game. Let's say the 'boss' has 10 millio ...

Is there a way to convert a string containing a date calculation, such as "now + 1 day", into a date object?

Currently, my team is utilizing Cucumber to define our test cases within string-based feature files. Our integration tests are executed against a wiremock stub that contains date calculations such as: "{{now offset='+15 minutes'}}" I am seeking ...

Using the goBack function in React Router does not add the previous location to the stack

In React Router v4, I have a list page and a details page in my web application. I want to implement a 'Save and close' button on the details page that redirects the user back to the list page when clicked. However, I noticed that after the user ...

Is there a way to incorporate vue samples into an independent HTML document?

Striving to broaden my knowledge of Vue, I set out to create a page with tabs inspired by one of the Vue examples available at . However, an obvious error seems to be eluding me, as I encounter a syntax issue on the line import * as Tabs from 'vue-s ...

Guide on how to initialize a variable in Express.js within a conditional statement in Node.js

Trying to create a variable based on a conditional statement, but even with simple code I am unable to retrieve the new variable. Here is my code: exports.productPatch = (req, res, next) => { const id = req.params.productId; const image = req.body.p ...

Issues with date clicking on FullCalendar in Angular

I'm currently using version 4.4.0 of the FullCalendar plugin, but I am facing an issue where the dayClick event is not being triggered in my code. Below is a snippet of my code: calendar.component.html <full-calendar defaultView="dayGridMonth ...

Puppeteer - Issue with Opening Calendar Widget

Problem: Unable to interact with the calendar widget on a hotel website (). Error Message: Node is either not clickable or not an Element Steps Taken (code snippet below): const puppeteer = require('puppeteer') const fs = require('fs/promi ...

The display of website content across various screens

I'm relatively new to creating websites using scripts, CSS, etc. But I feel like I'm getting the hang of it pretty well... Now I've reached a point where I want my site to look good on different screen resolutions. Currently, I have somethin ...

Using React: Implementing conditional checks within the render() method of functional Components

When working with my usual React class Components, I typically perform some checks within the render() method before returning conditional html rendering. However, when using a react functional component, I noticed that there is no render() method availabl ...

The intersection observer fails to detect any new elements or entries that are appended to the page after it has

When I press the "add section" button to create a new section, the intersection observer does not seem to observe it. Even when I try to run the observer again after pressing the button, it still doesn't work. I suspect that I need to reassign the `se ...