Identifying the similarities between strings and array elements in JavaScript

I am facing an issue where I have a list of values stored in a comma-separated string and I need to compare them against an array to see if any match. The goal is to return true or false, but I keep getting an undefined error.

const reqRights = ["18900253","3217840","1053"]; 
const groups    = "3217635,18272308,1053,3217633,18900253,3217698,3217699,3217840,10162510";

function checker(value) {
  var groups = groups.split(",");
  console.log(groups);
  return groups.every(function(v) {
    return value.indexOf(v) !== -1;
  });
}

arr = reqRights.filter(checker);
console.log(arr); 

It's important to note that the js engine SpiderMonkey 1.8 does not support .includes and some methods

Answer №1

Make sure to use const for groups as it prevents reassignment. Additionally, consider moving the groups.split(",") outside of the checker function to avoid creating a new array on every function call.

Instead of using every, utilize some to check if the regRights item is present in the groups array.

const reqRights = ["18900253","3217840","1053"]; 
const groups = "3217635,18272308,1053,3217633,18900253,3217698,3217699,3217840,10162510";

const groupsArray = groups.split(",");

function checkGroupValue(group) { 
   return group === value;
}

function checker(value) {
  return groupsArray.some(checkGroupValue);
}

arr = reqRights.filter(checker);
console.log(arr); 

Answer №2

let requiredPermissions = ['18900253','3217840','1053']; 
let allGroups = '3217635,18272308,1053,3217633,18900253,3217698,3217699,3217840,10162510';

function permissionChecker(value) {
  let groups = allGroups.split(',');
  return groups.every(val => groups.indexOf(val) !== -1);
}

let matchedPermissions = requiredPermissions.filter(permissionChecker);
console.log('Matching elements: ', matchedPermissions.length ? 'Yes' : 'No'); 

Answer №3

I wanted to steer clear of using indexOf to avoid any potential false positive results (for example, reqRight "1053" showing up when found in "1053568"). While this may not be the most concise solution, it is designed to be compatible with spiderMonkey 1.8.

const reqRights = ["18900253","3217840","1053"]; 
const groups    = "3217635,18272308,1053,3217633,18900253,3217698,3217699,3217840,10162510";

function checker(values, required) {
  var valuesArray = values.split(",");
  return valuesArray.filter((value) => {
    return required.filter((req) => {
      return req === value; 
    }).length > 0;
  })
}

arr = checker(groups, reqRights);
console.log(arr);

Answer №4

Utilize the Array.find method to filter out values from the groups array:

const reqRights = ["18900253","3217840","1053"]; 
const groups    = "3217635,18272308,1053,3217633,18900253,3217698,3217699,3217840,10162510";
const checker = value => 
 ({[value]: reqRights.find(v => value === v) ? true : false});
const checked = groups.split(`,`).map(checker);
console.log(checked);

Alternatively, combine both arrays (treating groups as an array), sort them numerically, and then filter out duplicate values.

const reqRights = ["18900253","3217840","1053"]; 
const groups    = "3217635,18272308,1053,3217633,18900253,3217698,3217699,3217840,10162510";
const checked = groups.split(`,`)
  .concat(reqRights)
  .sort( (a, b) => +a - +b)
  .filter((v, i, self) => self[i+1] === v);
  
console.log(checked);

Answer №5

To accomplish this task, you can utilize the combination of Array.map() and Array.some() methods.

Check out the example below for a demonstration:

const requiredRights = ["18900253","3217840","1053"]; 
const userGroups = "3217635,18272308,1053,3217633,18900253,3217698,3217699,3217840,10162510";

const result = userGroups.split(',').map(group => {
    return requiredRights.some(right => group === right)
});

console.log(result);

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

Texture mapping in THREE.JS can be applied to ExtrudeGeometry for enhancing the appearance

Currently, I am tackling an issue concerning three.js and ExtrudeGeometry. The challenge at hand involves a wave-like structure composed of multiple individual frames, each being extruded using ExtrudeGeometry. https://i.sstatic.net/juEBb.jpg My goal is ...

Using the array.prototype.map method on props in React.js results in an array that is devoid

Recently, I've started exploring the world of React and encountered a problem while attempting to convert the value of props into a JSX element using array.prototype.map(). You can learn more about this method at this link. Here is a snippet of a Rea ...

JS ddsclick is not a defined function

Here is the code snippet I am working with: <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script> <script type="text/javascript" src="<%:ResolveUrl("~/Content/JS/jquery.ddslick.min.js")%>" ></scr ...

Tips for resolving a flickering issue that occurs when switching to an input field with our default value / placeholder plugin

In the realm of web development, numerous plugins cater to the implementation of HTML5's placeholder attribute in older browsers. The plugin we have opted for can be found here. Unlike some other alternatives, this particular plugin, with a few modif ...

Convert Time: segment time devoted to the main content from the time dedicated to advertisements

Can anyone assist me with solving a math problem? Let's consider two lists or arrays: Content Array 0-50 = C1 50-100 = C2 AD Array 10-20 = A1 30-60 = A2 80-140 = A3 The desired output should be: 0-10 = C1 10-20 = A1 20-30 = C1 30-60 = A2 60-80 = C ...

Restrict certain links from being clickable until the page has finished loading and all click events have been bound using

I developed a modal dialog plugin using jquery, designed to link to the click event of each <a> element with a specific class. This modal dialog uses AJAX to 'fetch' a page declared under the 'href' parameter of the <a> el ...

Convert the array column in PostgreSQL containing tstzrange data types to an array column with tsrange

I currently have PostgreSQL tables structured like this: CREATE TABLE event ( id uuid PRIMARY KEY, time_zone text NOT NULL, start_date timestamptz NOT NULL ); CREATE TABLE event_user ( id uuid PRIMARY KEY, event_id uuid NOT NULL REFERENCES event ...

Add a new row to the table when a dropdown option is selected, and remove the row when deleted. Ensure that the row is only added

Here is my specific requirement: I need a table with a default row containing a dropdown menu in the first column. When an option is selected from the dropdown, a new table row should be added with the same content as the main row and a delete button for ...

The JavaScript code created in CodePen doesn't seem to function properly when integrated into my website

During a learning program, I created a basic random quote generator. The code worked flawlessly on codepen.io. Using a simple JavaScript (jQuery) function, I displayed random quotes along with their authors, which were stored in an array. I ensured that t ...

What is the best way to choose two <li> elements with multiple classes in my WordPress navigation menu?

I am looking for a JavaScript function that will add the class "current_highlight" when an element with the class "activo2" also has the class "active". Here is my HTML code: <div class="navbar-header"> <button type="button " class="navbar-to ...

Problem with character encoding in Node.js

I am encountering an issue while retrieving data from a request, as the formatting or encoding is not matching my requirements. Attempted to address this by setting the encoding with req.setEncoding('utf8') The expected string should appear as: ...

In node.js, session variables become null when the page is refreshed

Recently, I made the switch from PHP to node.js for my backend development. While working with session variables, I encountered an issue where the value displayed by console.log() on line 34 after reloading differed from the value on line 50 before reloadi ...

Refine an Array by applying multiple filters

Here is a simple JSON array that I have: const personList = [ { id: 1, name: "Phil" }, { id: 2, name: "Bren" }, { id: 3, name: "Francis Underwood" }, { id: 4, name: "Claire Underwood" }, { id: 5, name: "Ricky Underw ...

Strategies for managing the "ref" property of Material-UI component props within our custom components

I have a unique custom component setup as shown below: // ... import { PaperProps, styled } from '@mui/material'; type ComponentProps = PaperProps & { a: string, b: string }; export const MyPaper = styled(Paper)(/* ... */); const Compo ...

Menu secured in place within the wrapper

My website is contained in a wrapper with a max width, and I have a fixed side menu that can be toggled with a button. The problem I am facing is keeping the fixed side menu within the page wrapper. Fixed elements are typically positioned relative to the ...

Creating an empty array of objects in Vue 3 requires using the Vue 3 syntax

In my project using Vue3 with Nuxt, I encountered an issue. My goal is to initialize an empty array of objects and then populate it. let results = ref([]); results.value = [ { "name": input.value, } ...

What is the best way to save an object in a variable in MeteorJS/React for future retrieval?

This code snippet is located at the bottom of a component called 'Block'. export default theBlockContainer = createContainer(({ params }) => { return { voteStatus: Meteor.user()['listofvoted'], } }, Block); Although the ...

Data is not appearing as expected in the React component when using the data

I'm currently facing an issue while working with MUI. I am able to retrieve the list in console.log, but nothing is being displayed on the screen - no errors or data, just the console.log output. Here is a snippet of the data that I am receiving: ...

The input field is not functioning properly within the vue-drag-resize component

I have incorporated vue-drag-resize from https://github.com/kirillmurashov/vue-drag-resize in my project. Unfortunately, I am facing an issue where I am unable to focus and type anything inside an input text field that is contained within the vue-drag-res ...

Triggering a JQuery slider event on each individual slider handle within the range

Can events be triggered based on the movement of individual slider handles? I am curious because I need to dynamically update a datepicker depending on which handle is moved. However, I'm unsure if there is a way to: Specify an event for a specifi ...