What is the best way to utilize the _.uniq function in underscore to efficiently track and distinguish between even and odd numbers?

Just getting started with JavaScript and I've made some progress. My goal is to use underscore to display two sets of unique even and odd numbers on the console, but I seem to have hit a roadblock at about 90% completion.

var arr = ([1,3,5,2,0,4,5,2,9,9,8,2]);            
sort(arr);

function sort(arr) {

var evens = [];
var odds = [];                        
for(var i = 0; i < arr.length; i++) {            
    if(arr[i] % 2 ){            
        odds.push(arr[i]);            
    } else if(!(arr[i] % 2)) {            
        evens.push(arr[i]);            
}            
}            

console.log("ODD NUMBERS:" + " " + odds);            
console.log("EVEN NUMBERS:" + " " + evens);            
if(_.uniq(evens).length != evens.length || _.uniq(odds).length != odds.length){            
console.log("FAIL!");            
}             
}

Answer №1

To start, sort your array by separating the even and odd numbers, then utilize _.uniq

var arr = [1,3,5,2,0,4,5,2,9,9,8,2];

var evens = _.filter(arr, function(num){ return num % 2 == 0; });
var odds = _.filter(arr, function(num){ return num % 2 != 0; });

console.log("EVEN NUMBERS: "+_.uniq(evens));
console.log("ODD NUMBERS: "+_.uniq(odds));
<script src="http://underscorejs.org/underscore-min.js"></script>

Answer №2

arr[i] % 2 results in 0, which is equivalent to false in the condition of an if statement.

if (arr[i] % 2 === 0) { 
  // this code block executes when the number is even
} else {
  // this code block executes when the number is not even
}    

Answer №3

Uncertain if I have correctly understood your needs, however, below is a solution using ES6.

filter method is well-supported across most browsers and allows for better array manipulation in a declarative manner.

const arr = [1,3,5,2,0,4,5,2,9,9,8,2]; 
const isEven = el => el % 2 === 0;
const isOdd = el => el % 2 !== 0;
const evens = arr.filter(isEven);
const odds = arr.filter(isOdd);
console.log(`Unique evens: ${_.uniq(evens)}`); // => "Unique evens: 2,0,4,8"
console.log(`Unique odds: ${_.uniq(odds)}`); // "Unique odds: 1,3,5,9"

Answer №4

Primary issue:

ReferenceError: _ is not defined.

Make sure that you have included the Underscore library in your HTML file using
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
, or that Underscore has been properly required in your JavaScript file.

Secondary problem: "I expect no errors and both lists to be displayed in the console with distinct values."
This expected outcome isn't occurring because you need to execute the uniq function on the arrays. Simply wrap the two arrays with _.uniq() as shown below:

console.log("ODD NUMBERS:", _.uniq(odds));
console.log("EVEN NUMBERS:", _.uniq(evens));

Alternatively, you can apply _.uniq to the input array before sorting it, which will optimize processing time during sorting.

Regardless of the approach taken, assuming that Underscore is correctly implemented, the desired results should be achieved.

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

The organization of C arrays

I am struggling to articulate my question about how C arrays are stored in memory. Let me try to explain it the best I can. Imagine we have a three-dimensional array: int foo[2][3][4]; To access elements, we can use either array notation or pointer notat ...

Using Google scripts for sending POST requests with HTMLRequest

I am attempting to authenticate my account for DirectEnergie using Google App Script. When I make the request on POSTMAN with Chrome, it works perfectly fine. However, when I try to run the same script as shown below, it simply returns the HTML of the firs ...

Phase 2 "Loading" visual backdrop

I'm attempting to include a loading animation GIF in my Cycle 2 plugin. Is there a way to ensure that the GIF loads before the images? Right now, I have set my loading.gif as a background image. The issue is that the loading.gif isn't displaying ...

Typescript Angular2 filtering tutorial

In Angular 2 using TypeScript, the goal is to search for matching values from an array within an object array. The intention is to filter out any objects where the 'extraService' property contains any of the values from the 'array_values&apo ...

jQuery parseFloat causing loss of precision in price values

The code extracts a price value from a hidden input field named '#orginalAddon', then adds the cost of additional addons to this value and displays the total amount to the user. However, there seems to be an issue with truncation when the value i ...

Reduce the density of x-axis labels in highcharts

Do you have any input on Highcharts? This chart belongs to me: https://i.sstatic.net/OAjJJ.png I am looking to reduce the density of x-axis labels, similar to the y-axis. Your assistance is greatly appreciated. Edit: for instance, take a look at this ...

Are there any reliable charting APIs available that can efficiently handle the lazy-loading of large data sets using Ajax while scrolling or zooming?

Hey there! I need help finding a JavaScript charting API that allows me to query the server using specific bounds on the horizontal and vertical axes in order to retrieve new data points. Just to give you an idea, the dataset I'm working with is incre ...

Is there a way to retrieve a list of functions using ScriptEngine in Java?

I am using Jsoup to extract the JavaScript portion of an HTML file and store it as a Java String object. Furthermore, I am looking to extract lists of functions and variables within the JavaScript functions using javax.script.ScriptEngine. The JavaScript ...

Switch out bootstrap icons for angular material icons

I'm currently in the process of transitioning from using Bootstrap to Angular Material in an existing application. I need assistance with replacing the Bootstrap icons with Angular Material icons. Any help is greatly appreciated. <md-button class= ...

Can a javascript variable be accessed after loading an iframe and returning to the page?

Using a jquery plugin known as colorbox, my colorbox simply opens an iframe on the screen. This detail may not be relevant, as the core issue at hand is that I have 3 variables on my parent window that are retrieved from an AJAX call using jquery: data.re ...

Creating Dynamic Lists with React Native

<Search ref="search_box" onSearch={this.onSearch} backgroundColor="white" cancelButtonTextStyle={{ color: "red" }} placeholder="Search Food..." ...

Forces of Attraction and Repulsion in Three.js/Physijs: Exploring the Dynamics of Object

For my chemistry extra credit project, I am working on creating a 3D simulation that focuses on the atomic structure of compounds. My goal is to develop a visual representation of elements surrounding a central atom, such as fluorine surrounding nitrogen i ...

Error encountered while attempting to parse JSON data: cannot convert Array to String implicitly

Currently working with Rails 4.2.3 and attempting to parse JSON data using the following code: content = ["{\"sEcho\":3,\"timestamp\":1464705752942,\"iTotalRecords\":1242,\"iTotalDisplayRecords\":1242,\"aaData& ...

Discover the magic of Rails with fullcalendar

When I add an event click in my fullCalendar script in events.js.cofee, it crashes with turbolink. SyntaxError: [stdin]:7:24: reserved word 'function' <%=javascript_include_tag 'application', 'data-turbolinks-track' => ...

Retrieve a single element from a nested array using Mongoose

Here is the schema I am working with: const ElectionScheme = new mongoose.Schema({ id:{ type: Number }, description:{ type: String }, startDate:{ type: Date }, closeDate:{ type: Date }, certificatesMaxAmount:{ type: Number }, voters:[{ ...

When using VueJS to load an SVG file based on a variable within a for loop and utilizing v-html, the result returned is "[

I'm faced with a challenge of loading SVGs saved in separate files based on the content within a loop. Upon page load, what I see is: https://i.sstatic.net/OiwyT.png Hey there, check out my code snippet below: <div v-for="(rec, index) in stats ...

Ways to acquire the reference of the parent component

Within my code, there is a parent component represented as: <Parent> <Child (click)=doSomething()></Child> </Parent> I am looking to establish a reference to the Parent component in order to pass it within a method that will trigg ...

Tips for positioning a sticky div underneath a stationary header

I'm currently utilizing Bootstrap 4 for my project, and I am encountering an issue with maintaining a div that has the class "sticky-top" just below a fixed navbar. Despite attempting to use JavaScript to replace the CSS while scrolling, it hasn' ...

PHP script not being triggered by Ajax upload

After identifying and fixing errors through the Chrome console log, I am facing a new issue where the PHP script responsible for processing the data is not being called. <legend><strong>Choose a machine model</strong></legend> < ...

Can one execute two .click method calls consecutively in JavaScript?

My JavaScript code looks like this: function AutoClickButtons() { document.getElementById('Button1').click(); document.getElementById('Button2').click(); } Oddly, only Button2 is being clicked when I run the function. But if I s ...