Utilizing Lodash to extract properties, dividing arrays, and obtaining distinct values

I found a more effective method to accomplish the task in my JavaScript project by utilizing the Lodash library. The approach involves extracting properties, splitting arrays, and obtaining unique values.

  var taskobj = [
{'taskno':'a', 'team':'1,2'},
{'taskno':'b', 'team':'3,4'},
{'taskno':'c', 'team':'2,4'},
];

//Iterating through the object to convert strings into arrays
_.forEach(taskobj, function(value, key) {
taskobj[key].team = _.split(taskobj[key].team,',');
});

// Using _.map to extract teams and return an array
// Utilizing _.flatten to flatten the array
// Applying _.uniq to obtain unique values from the flattened array

return _.uniq(_.flatten(_.map(taskobj,'team')));
// Output - [1,2,3,4]

Do you think this is the most efficient way to achieve the desired outcome?

Answer №1

Utilize the reduce method along with initializing a new Set() and adding the values of team each time (subsequently converting it back to an array using the spread operator)

var taskobj = [
  {'taskno':'a', 'team':'1,2'},
  {'taskno':'b', 'team':'3,4'},
  {'taskno':'c', 'team':'2,4'},
];

var result = [...taskobj.reduce((acc, {team}) => {
  team.split(',').forEach(e => acc.add(e))
  return acc
}, new Set())]

console.log(result)

Answer №2

To accomplish this task, you can utilize the lodash#flatMap method along with an iteratee function that breaks down the team string into an array. This array is then flattened using the mentioned function and finally, the lodash#uniq function is applied to retrieve the desired outcome.

var result = _.uniq(_.flatMap(taskobj, ({ team }) => team.split(',')));

var taskobj = [
    {'taskno':'a', 'team':'1,2'},
    {'taskno':'b', 'team':'3,4'},
    {'taskno':'c', 'team':'2,4'},
];

var result = _.uniq(_.flatMap(taskobj, ({ team }) => team.split(',')));

console.log(result);
.as-console-wrapper{min-height:100%;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Answer №3

Utilize a more straightforward version

Give this a shot


var teams = [];
var taskobj = [
      {'taskno':'x', 'team':'5,6'},
      {'taskno':'y', 'team':'7,8'},
      {'taskno':'z', 'team':'6,8'},
    ];

taskobj.map(obj => {
  var teamSplit = obj.team.split(',');
  teams = [...teams, ...teamSplit];
})

var uniqTeams = _.uniq(teams);
console.log('teams', teams);
console.log('uniqTeams', uniqTeams)

Check out the JsBin link http://jsbin.com/bedawatira/edit?js,console

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

Disabling and enabling a link before and after an AJAX call using jQuery

I have been trying to disable a link before making an ajax call and then re-enable it right after receiving the response. However, my current approach doesn't seem to be working as expected: jQuery(this).prop('disabled', false); Here is my ...

What is the best way to trigger the Javascript blur event following a click event that results in the element losing focus

Encountering this issue multiple times has left me dissatisfied with the solutions I've implemented in the past. The challenge lies in dealing with an input box that triggers a validation process on blur, while also having a button that populates the ...

Reorder a specific character within an array using Javascript

I am a beginner in JavaScript and I'm hoping for some assistance. I have an HTML list with a select option, and I want to sort the list based on the selected character. Specifically, I would like to arrange the "Z" options first, followed by the "B" ...

An easy way to showcase Wikipedia's JSON data using JQuery

I would like to showcase the information found in the "extract" section of this JSON data retrieved from Wikipedia: { "query": { "normalized": [ { "from": "india", "to": "India" } ...

Verifying Angular JS Routing: Ensuring the Current URL Matches the Route, including Dynamic URL Parameters

Just setting this up: app.config(['$routeProvider',function($routeProvider) { $routeProvider .when('/asd/:id/:slug',{ templateUrl:'views/home/index.html', controller:'Home', publicAccess:true, se ...

Verify if there are duplicate values present in a table

I have a Table that contains multiple rows, each row having input fields. I need to check for duplicate values within the table. Below is my code where I am currently checking for empty values, how can I modify it to also detect duplicate values? JavaScr ...

Using JavaScript to automate keystrokes programmatically

Is there a way to programmatically close a webpage using the keyboard shortcut control + W? I'm wondering if I can write code that will mimic this specific shortcut (control+W). ...

Unable to trigger Firebase callable function

Currently, my project is utilizing the Vue framework. I have integrated Firebase services, including Firestore, realtime database, triggered cloud functions, and onCall functions. Everything was functioning properly until recently when all of the callable ...

When the div is loaded, automatically navigate to the crucial li element within it, such as the one with the class "import

Welcome to my first webpage: <html> <head> <script type="text/javascript" src="js/jquery.min.js"></script> </head> <body> <div id="comment"></div> <script type="text/ja ...

The issue arises when a continuous use of angularjs directives linked with an external template fails to display correctly upon the addition of new

In the code snippet below, you'll find a fiddle that displays 3 columns of numbers that increase in value. These columns represent directives with different templates: one inline, one preloaded, and one from an external template. When you click on the ...

Is it feasible to replicate an error in TypeScript with certain modifications?

Currently, I'm facing a challenge where I need to utilize Sentry.captureException with an error that I have received. However, before doing so, I am attempting to modify the error message. Despite spending considerable time searching for a solution, I ...

Issue encountered while processing data from the file

Sorry if this question has already been addressed, but I couldn't find a solution through my search efforts. I'm currently working on a program that reads from a file containing lines with one name followed by five integers. My goal is to read t ...

Passing data between pages using React Native hooks

I am a newcomer to React Native and facing challenges in passing data to another page. Specifically, I want to transmit data from the QR Reader to another Page. Below is my code on the first screen: const LoginScreen = (props) => { const onSucce ...

When attempting to connect to the MongoDB cloud, an unexpected error arises that was not present in previous attempts

npm start > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="650800170b4816001713001725544b554b55">[email protected]</a> start > nodemon index.js [nodemon] 3.0.2 [nodemon] to restart at any time, enter ...

Unable to automatically close browser window after test execution with NightwatchJS

I recently executed my first Nightwatch test, as indicated in the code below. The test ran smoothly - Selenium successfully entered 'wiki' into Google and submitted the form, resulting in a passing test. However, I am now looking to automate the ...

Is there a way to use jQuery to adjust the text color once it has been clicked on?

I have been struggling to change the text color upon clicking on it without any success. Within my code, there are seven labels - one for the question, four for the answer options, one for the correct answer, and the last one for the explanation. The desi ...

What is the process for converting all elements in an array of strings to lowercase?

Within the following function, I am required to generate a list of all duplicate strings in a hash table. In case the parameter's value is equal to 1, cases are disregarded. upo_strings_list_t upo_find_idup(const char **strs, size_t n, int ignore_case ...

react-responsive: The children of a Responsive component do not have the capability to receive props

Utilizing the typical scenario described in the README file: const Desktop = props => ( <Responsive {...props} minWidth={1680} maxWidth={2560} /> ) const LaptopL = props => ( <Responsive {...props} minWidth={1440} maxWidth={1679} /> ...

Unable to simulate the navigator.language

I'm currently in the process of writing unit tests for some of my shared utility functions. As someone who is relatively new to unit testing, I am encountering difficulties when trying to mock certain global objects. Specifically, I am struggling to f ...

Is there a way to prevent camera motion in three.js when the escape key and directional keys are activated?

While working on my project with Pointer Lock Controls, I came across a bug. When the player is pressing any directional keys on the keyboard and simultaneously presses the escape button to turn off the Pointer Lock Controls, the camera continues to move ...