What is the best way to arrange two objects depending on the frequency of elements in an array field?

Imagine having two objects, each containing two array fields:

const list1 = {
  name: 'list-1',
  fruits: ['banana', 'strawberry', 'cherry'],
  vegs: ['lettuce', 'avocado', 'beans']
};

const list2 = {
  name: 'list-2',
  fruits: ['banana', 'apple', 'orange', 'watermelon'],
  vegs: ['potato', 'avocado', 'onion', 'cabbage']
};

Now, if you were to provide two arrays, one for fruits and one for vegetables, such as:

const fruits = ['banana', 'strawberry'];
const vegetables = ['potato', 'lettuce', 'avocado'];

How would you go about arranging the objects so that the one with the most number of matching fruits and vegetables (based on the provided arrays) is placed on top?

In this scenario, list1 would take precedence as it contains both "banana" and "strawberry" in fruits, as well as "lettuce" and "avocado" in vegs (totaling 4 matches), while list2 only has 2 matches overall.

If this explanation seems convoluted, what would be the most effective method for prioritizing the objects based on the arrays?

Answer №1

To start, you should create a custom intersection function that takes two lists as input and returns a new list with only the common elements. You can find a detailed explanation here if you prefer to write your own implementation, or you can use existing libraries like Ramda or Lodash. It's a good idea to have a reusable function for future use, even though you can include it within your sorting function.

Once you have the intersection function ready, you can create a custom comparison function for sorting objects similar to list1 and list2 based on your specified criteria. Here's an example:

const compareByTotal = (a, b) => {
    const aTotal = intersection(a.fruits, fruits).length + intersection(a.vegs, vegetables).length;
    const bTotal = intersection(b.fruits, fruits).length + intersection(b.vegs, vegetables).length;
 
    return bTotal - aTotal;
}

Finally, you can utilize this comparison function as an argument in the sort method to generate a sorted list of these objects:

[list1, list2].sort(compareByTotal);

Answer №2

It seems like you're asking about organizing your objects into arrays and sorting them. One way to achieve this is by creating separate arrays for each object, then utilizing the Array.Prototype.sort method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

For example:

const data1 = {
  name: 'data-1',
  numbers: [1, 2, 3, 4],
  letters: ['a', 'b', 'c']
};

const data2 = {
  name: 'data-2',
  numbers: [1, 2, 3, 4, 5],
  letters: ['x', 'y', 'z']
};

const arrayOfData = [data1, data2]

arrayOfData.sort((a, b) => (a.numbers.length + a.letters.length) < (b.numbers.length + b.letters.length) )

console.log(arrayOfData) // Output = [data2, data1] since data2 has more numbers and letters

Answer №3

One effective method is to loop through the lists, assign a score to each item, and then determine the winner based on the scores. Here is a sample implementation:

const list1 = {
  name: 'list-1',
  fruits: ['banana', 'strawberry', 'cherry'],
  vegs: ['lettuce', 'avocado', 'beans']
};

const list2 = {
  name: 'list-2',
  fruits: ['banana', 'apple', 'orange', 'watermelon'],
  vegs: ['potato', 'avocado', 'onion', 'cabbage']
};
const fruits = ['banana', 'strawberry'];
const vegetables = ['potato', 'lettuce', 'avocado'];
const selectAWinner = (fruits,vegetables)=>{
    let list1Score = 0;
    let list2Score = 0;
    fruits.forEach(fruit=>{
        list1.fruits.forEach(fruitFromTheList=>{
            if (fruitFromTheList === fruit)
                list1Score++
        })
    })
    vegetables.forEach(vegetable=>{
        list1.vegs.forEach(vegetableFromTheList=>{
            if (vegetableFromTheList === vegetable)
                list1Score++
        })
    })
      fruits.forEach(fruit=>{
        list2.fruits.forEach(fruitFromTheList=>{
            if (fruitFromTheList === fruit)
                list2Score++
        })
    })
    vegetables.forEach(vegetable=>{
        list2.vegs.forEach(vegetableFromTheList=>{
            if (vegetableFromTheList === vegetable)
                list2Score++
        })
    })
    if (list1Score > list2Score)
    document.write("list 1 wins with score " + list1Score)
    else if (list1Score < list2Score)
    document.write("list 2 wins with score " + list2Score)
    else document.write("it's a tie")
    // or do something else with the results
}
selectAWinner(fruits,vegetables)

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

What is the method for retrieving a value using the Angular forEach function?

I'm encountering an issue with retrieving values from an angular forEach loop. Below is the data I am working with: vm.memberDetails={ "member": [ { "firstName": "HARRY UTTWO", "lastName": "POTTER", } ...

Search for the next input using jQuery, then trigger a select event on keypress excluding any buttons

Is there a way to modify my code so that when the user presses "enter", it selects the next visible input or select element, without including buttons in this selection? $(document).on('keypress', 'input, select', function (e) { if (e. ...

What is the best way to show an error message on a field when using a custom form validator?

In my JavaScript code, I have created a form validator that is capable of validating different input fields based on specific attributes. However, I need assistance with implementing error handling and scrolling to the erroneous field. For each <input& ...

Vows.js: Utilizing data from parent topics in nested topics

Is there a way to access the return value of an outer topic from within a test in an inner topic? To clarify, consider this example: "build.css" : { topic : function(file) { fs.readFile(fixtures + "/public/build.css", "utf8", this.callback); }, ...

Update the content in the Bootstrap modal

I'm currently implementing modal Bootstrap in my ASP.NET website. I have encountered an issue where the text in the modal does not change according to the errors returned in the code behind, even after modifying the text value of the control before ma ...

Create interactive highcharts graphs using data from a CSV file generated through PHP

I'm having trouble working with Highcharts and csv data. Take a look at this example: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-ajax/ $.getJSON('http://www.highcharts.com/ ...

Generate a collection of information by gathering metadata from Xray

I've been struggling to populate an array with metadata retrieved using Xray. The issue arises when the function is called by an API endpoint on my server to fetch links from my application. My main challenge seems to be related to promises, as there ...

What is the process for adding an event listener in React?

Currently, I am working on a chat application that involves both users and agents. I am facing an issue where I need to retrieve messages when the agent responds using a separate Rainbow UI. According to the documentation, this can only be achieved using a ...

How to replicate Javascript's 32-bit signed integer arithmetic in C (or Perl) with a few differences

I have encountered a discrepancy when translating simple JS code to C and/or Perl, specifically related to arithmetic operations (+ - * / << >>) on integers causing overflow. My goal is to replicate the exact behavior of JS, including handling ...

Interactive navigation through scrolling with PHP onchange event

I need help with a PHP-related issue. I have a list of products that are generated dynamically using PHP. When a user clicks on one of the items in the list, the products are sorted. I also want the user to be smoothly scrolled to a new section of the page ...

Animation fails to initiate when the object enters the viewport

I attempted to inject some enchantment into my project by implementing code from a tutorial found on this CodePen. However, I encountered an issue where the code only functions properly within that specific CodePen environment. Even after copying the same ...

` ` Despite entering correct values, the HTML form is still displaying validation errors due to JavaScript. ``

My contact form with validations is functioning well, but I am facing an issue where old errors persist even after correcting them and submitting the form again. Below is a snippet of the document containing the JavaScript code: <form id="contactForm" ...

Encountering an issue with a class component stating that "this.setState is not a function

I am currently learning React JS and encountered an error when calling my first API in React. I keep getting the message "Unhandled Rejection (TypeError): this.setState is not a function." I have been trying to troubleshoot this issue on my own but haven ...

AngularJS uses two ng-repeat directives to manage and manipulate data in

I'm implementing a feature where I have two views in my HTML5 code that display the same list. <div class="list" data-ng-repeat="item in model.items"> <div class=list-item"> {{ item.name }} <a data-ng-click="addToLi ...

Accessing PHP variables in JavaScript

Hi there, I am new to all this. I am trying to figure out how to use a PHP variable in JavaScript. Here is a snippet of my code (popup.php): <?php $id_user = $this->session->userdata('id'); ?> <script type="text/javascript"> ...

Creating a radio button along with a submit button that redirects to a different local HTML file

Can someone please help with this code? I'm trying to redirect to the value of each radio button when it's clicked. Any guidance or JavaScript code would be greatly appreciated. Thank you. I've tried multiple solutions but none of them seem ...

What is the best way to ensure the initial item in an accordion group remains open by default when using NextJS?

I've successfully developed an accordion feature in NextJS from scratch and it's functioning flawlessly. However, I am looking to have the first item of the accordion open automatically when the page loads. Can anyone guide me on how to make this ...

Text inside the placeholder is not displaying correctly in the React.js user interface

When passing placeholder text as a prop to the <FormField/> component from the <CreatePost/>, I encountered an issue where the placeholder text was not displaying in the form. Interestingly, when I used console.log within the <FormField/> ...

Error: An unexpected character was found in the Gulpfile.js

Having an issue in my Gulpfile.js: gulp.task('webpack', gulp.series(async () => { const option = yargs.argv.release ? "-p" : "-d"; execSync(`node_modules/webpack-cli/bin/cli.js ${option}`, { stdio: [null, process.stdout, proce ...

Ajax login feature not redirecting to login popup after successful login

When attempting to open a popup by clicking on the login window, a pop-up appears with a URL requesting username and password along with Google sign-in. However, when a user tries to log in using Google sign-in through the pop-up, it fails to redirect to ...