Enumerating the Elements in a List, Including them in 2 Entities inside a List

var arr = ['cat','cat','dog','penguin','chicken','chicken']

function orgAnimals(input)
   var obj = {};
   for (var i = 0 ; i < input.length; i++) {
      obj[input[i]] = obj[input[i]] || 0;
      obj[input[i]]++
   }
return obj;
}

After running the function, I get {cat:2, dog:1, penguin:1, chicken:2,}

My goal is to divide this object into two separate objects and then put them in an array like so:

[{cat:2, dog:1} {penguin:1, chicken:2 }]

I attempted to use an if statement to achieve this but it did not produce the desired outcome. if (input[i]==='cat'||'dog') still returned the original result.

Any suggestions or hints? Could it be the way I'm using the logical operator?

Answer №1

Golf time, perhaps

var arr = ['cat','cat','dog','penguin','chicken','chicken']

function organizeAnimals(input) {
    return input.reduce((a, b) => {
    var index = ['cat','dog'].indexOf(b) === -1 ? 1 : 0;
      return b in a[index] ? a[index][b]++ : a[index][b] = 1, a
    }, [{},{}]);
}

console.log( organizeAnimals(arr) );

Similar concept, but with improved readability, where we check if the current value is either cat or dog and add it to the array based on a condition

var arr = ['cat', 'cat', 'dog', 'penguin', 'chicken', 'chicken']

function organizeAnimals(input) {
    var arr = [{}, {}];
    
    for (var i = 0; i < input.length; i++) {
    
        if (input[i] === 'dog' || input[i] === 'cat') {
        if (input[i] in arr[0]) {
            arr[0][input[i]] = arr[0][input[i]] + 1;
            } else {
            arr[0][input[i]] = 1;
            }
        } else {
        if (input[i] in arr[1]) {
            arr[1][input[i]] = arr[1][input[i]] + 1;
            } else {
            arr[1][input[i]] = 1;
            }
        }
    }
    return arr;
}

console.log(organizeAnimals(arr))

Answer №2

To effectively achieve the desired outcome, it is recommended to first create two distinct objects and then consolidate them in the return statement. Here's an example of how this can be implemented:

if ((input[i] == 'elephant') || (input[i] == 'lion'))){
  object1[input[i]] = object1[input[i]] || 0;
  object1[input[i]]++
}
else if ((input[i] == 'tiger') || (input[i] == 'zebra')){
  object2[input[i]] = object2[input[i]] || 0;
  object2[input[i]]++
}
return {object1, object2}

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

Using Flexbox CSS to Expand a Box According to its Content Size, Without Impacting Adjacent Rows

Is there a way to make the bottom-most row (highlighted in yellow) expand downward to fill available space? Check out this link for reference: https://jsfiddle.net/darrengates/oucvnfke/ I initially thought using: flex: auto; would solve the issue. Whil ...

What is the best way to retrieve data from divs that are nested within another element using Javascript?

I am currently working on implementing a modal that will showcase specific information based on the event-card it originates from. Here is an HTML snippet showcasing an example event-card: <div class="event-card upcoming hackathon"> <d ...

Arrange divs adjacent to each other without any gaps in between

My HTML code includes elements from Twitter Bootstrap and AngularJS framework. <div class="item item-custom-first"> <select class="form-control" style="display:inline; float:right" ng-model="requestdata.units ...

Looking to create a pop-up using javascript, css, or jQuery?

When visiting digg.com and clicking the login button, a sleek in-screen popup appears to input user data. I'm curious about the best way to achieve this on my own site. It is built with RoR and includes some Javascript elements. Searching for "javasc ...

steps to invoke a class within a function

I'm currently attempting to invoke a model class from the Axios response. Instead of displaying an alert, I would like to show a modal popup. Can someone assist me with how to call the modal class from the Axios interceptor function? Thank you in adva ...

What is the standard way to write the server-side code for HTTP request and response handling?

I stumbled upon these resources: How to send HTTP request GET/POST in Java and How to SEND HTTP request in JAVA While I understand the client-side aspect, how can this implementation be done on the server side? The goal is to utilize the link on the clie ...

The JQuery pagination feature fails to function properly once an AJAX load is initiated

I am using jspages.js to implement pagination with jQuery. Everything works fine when the page is initially loaded. However, I encounter an error when the content for pagination is loaded after an ajax call. The plugin does not seem to work as expected. ...

Converting an array into JSON format in JavaScript without duplicate curly braces

Having two parallel mysql queries in node js is meant to retrieve data more efficiently. The following javascript code reads from a mysql database and stores the results in a javascript object: async.parallel({ aaChannelsCount: function(cb) { /* G ...

Updating Arrays within Arrays in BigQuery for GA4 Data

I need to perform an update on an array value in table1 using a value from another table. table1: event_params.key event_params.value.string_value country US table2: country new_country US NL I attempted the following query: UPDATE table ...

What is the best way to prevent the page from constantly refreshing?

Recently, I developed a code snippet that detects the user's geolocation and changes the currency accordingly. The functionality works as intended, but there is an issue where the page keeps refreshing due to the presence of certain code. If I remove ...

Ways to display a specific section on an HTML page using AngularJS

Main page content <div class="row"> <div class="col-md-3"> link 1 link 2 link 3 . . . </div> </div> <div class="col-md-9"> <div ng-view></div> </div& ...

Tips for sending form data via ajax to a python script?

I'm running into an issue with a python program and an ajax request. I am attempting to retrieve data from my Javascript in the python program, but the usual method of using .getfirst(field name) isn't working, which I believe is due to the reque ...

Having trouble populating a datalist with options sourced from a MySQL table, as the options do not consistently show up (Node.js)

My goal is to dynamically populate a datalist with option elements by querying a MySQL server using node. The requirement is that if the inputted text by the user matches any part of a university name in the database, that university should be displayed as ...

Cross Domain Requests in Internet Explorer: Preflight not being sent

I have come across several similar discussions but none of the solutions provided have worked for me so far. Issue: In our current setup, we have three servers hosting our http-apis - two for testing and one for production. Lately, we have been deployin ...

AngularJS has encountered an undefined form within its scope

In my main JavaScript file, I have a collection of functions that are used throughout my application. This JS file also handles the routing of the app. main.js (MainController): $stateProvider .state('page1', { url : '/&apo ...

retrieve all users who are not currently in the group

I'm currently struggling to retrieve all users who are not members of a particular group within a many-to-many association. After investing several hours into researching and experimenting, I've developed the following code. However, it falls sh ...

Update input box value using Javascript

Here is the code for a <script> tag on a webpage that includes an input box within the body of an HTML document- <script type="text/javascript" language="JavaScript"> window.onload = function addSearchText() { document.getElementB ...

Iterate through a nested array in JavaScript and extract specific properties by comparing them to another array

Within my code, there is a kids object structured as follows: const kids = { name: 'john', extra: { city: 'London', hobbies: [ { id: 'football', team: &apos ...

Are memory leaks a common issue with Angular directives?

Using a simple html file to replicate a memory leak: <!doctype html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular.min.js"></script> <script> va ...

The replace method for strings in JavaScript does not function properly on mobile devices

I encountered an issue with the string replace method I implemented on my website. Upon checking the page using the web browser on my Android phone, I noticed that it was not functioning as intended. Here's a snippet of the code: /*The function is ...