Discover the Replicated Element in a Set Using the Lodash Library

Trying to determine the existence of a value in a collection using Lodash.

If the value exists, return true; otherwise, return false.

 const d = [{
     "country": "India",
     "_id": ObjectId("5ad47b639048dd2367e95d48"),
     "cities": []
 }, {
     "country": "Spain",
     "_id": ObjectId("5ad47b639048dd2367e95d49"),
     "cities": []
 }];

Code Snippet:

Countries = ['India', 'Spain']
if (_.has(d, Countries)) {
    console.log(true);
} else {
    console.log(false);
}

However, it consistently returns False. If there is a more efficient way than utilizing lodash, I'm open to suggestions.

Answer №1

To check if any of the items in the "items" array contain a country from the "countries" array, you can utilize the `some` and `includes` methods. When executed, this code snippet will output `true` if there is a match found.

const items =  [
    {
        "country": "Japan",
        "_id": 'ObjectId("5ad47b639048dd2367e95d48")',
        "cities": []
    },
    {
        "country": "Germany",
        "_id": 'ObjectId("5ad47b639048dd2367e95d49")',
        "cities": []
    }
];

const countries = ['Japan', 'Germany'];
const includes = _.some(items, item => _.includes(countries , item.country));
console.log(includes);
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfd3d0dbdeccd7ff8b918e88918a">[email protected]</a>/lodash.min.js"></script>

Answer №2

ES6

To check for duplicate entries in an array, you can utilize array.some() and array.includes().

DEMO

const d = [{
  "country": "India",
  "_id": "5ad47b639048dd2367e95d48",
  "cities": []
}, {
  "country": "Spain",
  "_id": "5ad47b639048dd2367e95d49",
  "cities": []
}];

const Countries = ['India', 'Spain'];

console.log(d.some(({country}) => Countries.includes(country)))
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

Using plain Javascript instead of relying on Lodash, you can achieve the same functionality with the native filter method.

d.filter(item => item.country === "Spain"); // This will return an array of objects where the country's name is Spain!

To convert this into a boolean value, you can store it in a variable and check if its length is greater than 0:

let isSpanishCountry = d.filter(item => item.country === "Spain").length > 0; // console.log(isSpanishCountry) => true

Answer №4

Inspired by @Christian Bartram

var countries = [
  {country: "Japan",bOn:false},
  {country: "China",bOn:false},
  {country: "Korea",bOn:false},
  {country: "Vietnam",bOn:false}, {country: "Vietnam",bOn:true},
  {country: "Thailand",bOn:false}
];

//Identify duplicate element values in the array
_(countries).groupBy(x => x.country).pickBy(x => x.length > 1).keys().value()

Output

['Vietnam']

//Find duplicate objects in an array
_.filter(_(countries).groupBy(x => x.country).value(),x => x.length > 1)

Output

[[{"country":"Vietnam","bOn":false},{"country":"Vietnam","bOn":true}]]

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

Confirming the data entry format

I am currently utilizing the RobinHerbots/Inputmask plugin to mask telephone input. I am interested in finding out how I can implement input validation to ensure that the user has entered accurate information. Thank you! <form> <input ty ...

Merging the outcomes of a JSON call

Presently, I have an async function that returns a JSON response in the form of an array containing two objects. Please refer to the screenshot. https://i.sstatic.net/gCP8p.png How can I merge these objects to obtain: [{resultCount: 100, results: Array(1 ...

The code snippet 'onload='setInterval("function()",1000)' is not functioning as expected

I need to continuously load the contents of an XML file into a specific HTML div every second. Here is the JavaScript code that I am using to parse the XML file: function fetchEntries() { if (window.XMLHttpRequest) req = new XMLHttpRequest(); ...

Deactivate every checkbox in a row within an array

Seeking assistance with disabling a specific checkbox within a row. For example, Consider the following scenario {availableBendsHostnames?.map((bEnds, indx) => ( <div key={indx}> <div>B-End: {bEnds}</div> ...

How can I retrieve console log information in POSTMAN when a test fails?

Having an issue with this test. I am trying to trigger a console.log when the installment value in my JSON is less than 100 (resulting in a test FAIL). However, I am receiving both PASS and FAIL results in the test, but no information is showing up in th ...

Converting a string to JSON in Golang: A step-by-step guide

I am looking for a solution to convert a string into Json format and then return it. The values received via the POST request (writePost) using c.JSON(200, string(body)) are as follows: "{\"message\":{\"@type\":\"response&b ...

Adjust Scale to Less than 1 in JVectorMap

I am in the process of developing a website that includes a full-size map using JVectorMap. The map currently occupies 100% of the width and height of the page, but I would like to add a border around it when fully zoomed out. However, when the map is zoom ...

Issue with PHP $_GET function not functioning properly in conjunction with JQuery Mobile

I am currently developing an application using a combination of JQuery Mobile and PHP. The issue at hand is as follows: I am encountering difficulties when attempting to transfer values between different pages in my JQuery mobile app (for example, from #p ...

How can I ensure the Jquery datepicker functions correctly?

I've been attempting to create a jsp page with some Jquery functionalities. Unfortunately, despite my best efforts, I am unable to make it work. I have downloaded jquery1.7.1 and jquery-ui1.8.17 (non-mini), renamed them to jquery171.js and jquery-ui. ...

The transmission of information through Ajax is encountering a problem as the data is not properly

Having some trouble using Ajax to send form data and echoing it on the PHP page. Since I'm new to Ajax, I might have made a mistake somewhere in my code. Below is what I currently have: $(function () { $('form').on('submit&apos ...

The hermitian of a square matrix within a multidimensional NumPy array

How can we calculate the Hermitian matrix for a 2D matrix within a multi-dimensional np.array, such as the example of F with a shape of (3, 2, 2, 2)? The first two dimensions represent items in a specific category, with the data being a 2D matrix within th ...

Utilizing dynamic case class assignment within a class definition

We have a scenario where we are dealing with two distinct case classes each containing different parameters. Here is an example: case class FirstType(@JsonProperty("field1") field1 : String, @JsonProperty("field2") fi ...

What is the best way to differentiate the handling of a 401 Unauthorized response from other errors within an Angular 8 service that utilizes RxJS?

My REST API implementation requires an access token for user identification with each call. If the token is missing or expired, the endpoint returns a 401 UNAUTHORIZED response. There are instances where I make API calls using a timer in my service class: ...

Can a string be transformed into HTTP POST parameters?

Below is a snippet of code where I've utilized the .serialize() method to convert all form inputs into a string, which is then sent to the server: $.ajax({ type: "post", url: wp_urls.ajax_url, data: { action: "submit_form", ...

JavaScript allows for inserting one HTML tag into another by using the `appendChild()` method. This method

My goal is to insert a <div id="all_content"> element into the <sector id="all_field"> element using Javascript <section id="all_field"></section> <div id="all_content"> <h1>---&nbsp;&nbsp;Meeting Room Booki ...

Tips for ensuring a scrollbar remains at the bottom position

I'm facing an issue with a scroll-bar inside a div element. Initially, the position of the scroll-bar is at the top. However, whenever I add text to the div element, the scroll-bar remains in its initial position and does not automatically move to the ...

Transform the text column into JSON format

We currently have a resource bundle/properties formatted as follows: [tag1] server1 server2 [tag2] server3 server4 [tag3] server5 server6 [No Software Installed] server7 [tag2] server8 [tag5] server9 [tag1] server10 server11 [tag3] server12 server13 serve ...

Issue with Node REST API: PUT request is failing to update data in the request

Encountering issues while attempting to update data through a PUT request. Despite making the request, the data remains unchanged and continues to display the previous information in Postman. Details of the PUT request sent via Postman: http://localhost: ...

Utilizing vuetifyjs: Selectively incorporating necessary icons into the build

I am currently working on a vuetifyjs-app using the default "Material Design Icons". For the production build, I am only utilizing 2 icons from this font (which are being used by the vuetify-component chips). Following recommendations, I have included the ...

The functionality of the jQuery script is not operating optimally, causing the expected alert to not be displayed

I implemented this jQuery script: $('input[name="add-post"]').on('click', function(form) { form.preventDefault(); for ( instance in CKEDITOR.instances ) CKEDITOR.instances[instance].updateElement(); $.ajax({ typ ...