Cost-Effective Method for Refining Search Results of an Item

I am working with a JSON file containing movie data and I'm looking to extract only the top ten highest scoring movies:

Here is a snippet of the data:

{
    "movies" : {
        "eraserhead" : {
               "full_title" : "Eraserhead",
               "votes": 50
         },
        "psycho" : {
               "full_title" : "Psycho",
               "votes" : 90  
         }
    }
}

And so on for approximately 50-100 entries.

While I am aware that I can iterate through the data and create a list based on the scores, I am interested in knowing if there is a more efficient way to filter and retrieve the top ten movies based on the movies[title].votes property.

Any suggestions or guidance on this matter would be highly appreciated. Thank you.

Answer №1

To simplify things, you can create an array, sort it, and then select the first 10 elements.

var movieArray = [];
for (var index in films) {
    var film = films[index];
    film.name = index; 
    movieArray.push(film);
}
var topTenMovies = movieArray.sort(function(a,b){return b.likes-a.likes}).slice(0,10);

See it in action (open the console)

Answer №2

let moviesList = object.movies;
let moviesArray = [], key;
    
for (key in moviesList) {
    if (moviesList.hasOwnProperty(key)) {
        let movie = moviesList[key];
        movie.title = key;
        moviesArray.push(movie);
    }
}

let sortedMovies = moviesList.sort(function(a, b) {
    return a.votes - b.votes;
});
let top10Movies = sortedMovies.slice(0, 10);

Answer №3

When it comes to sorting, efficiency is key. To achieve this, you can follow the code snippet below:

var result = [],
    len, o;

for (var key in data.movies) {
    o = data.movies[key];
    len = result.length
    if (!len) {
        result.push(o);
    } else if (len < 10) {
        if (o.votes < result[0].votes) {
            result.unshift(o);
        } else {
            while (len--) {
                if (o.votes > result[len].votes) {
                    result.splice(len + 1, 0, o);
                    break;
                }
            }
        }
    } else if (o.votes > result[0].votes) {
        result.shift();
        if (o.votes < result[0].votes) {
            result.unshift(o);
            continue;
        }
        len--;
        while (len--) {
            if (o.votes > result[len].votes) {
                result.splice(len + 1, 0, o);
                break;
            }
        }
    }
}

http://jsperf.com/reduce-object-of-objects-to-max-property

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 Power of ReactJS Spread Syntax

Currently working with React. In the state, I have an array of objects. this.state = { team: [{ name:'Bob', number:23 }, { name:'Jim', number:43 }] } My issue arises when attempting to create a copy of the arr ...

Transferring Data between Rails and Angularjs using JSON

Utilizing Angularjs to fetch JSON data from a Rails test app deployed on Heroku is proving to be a bit challenging. Below you can find the snippets of my Angular and Rails code. An error message displayed in my Firebug console reads: "NetworkError: 404 N ...

Having trouble loading script files with JSDOM in NodeJS?

I'm currently experimenting with loading an HTML page in jsdom to generate graphs, but I'm facing challenges in getting the JavaScript to execute. Here's the HTML page I'm trying to load, which simply renders a basic graph: <html&g ...

Arrange and display similar objects together

I have a list of items in a listView that need to be visually grouped based on their class, displayed within boxes. For example, I have 5 items with the following classes: <div class="1"></div> <div class="1"></div> <div class= ...

What is the distinction between selecting and entering a date input value?

When a user selects a date, it needs to be immediately sent to the server. If they manually type in the date, it should be sent on blur. The issue arises when the oninput event is triggered for each keydown event, causing unnecessary server requests while ...

Tips for duplicating a collada model in three.js?

I've imported a .dae model into my scene and I want to use it multiple times. The code provided works with meshes, but the collada.scene object is not a mesh: var mesh2 = new THREE.Mesh( loadedMesh.geometry, loadedMesh.material ); Is there a way to ...

When trying to use TypeScript with next.js, encountering an unexpected token `?` error is not

Having an issue with next.js, the command npm run dev keeps failing due to a syntax error related to an optional property in a tsx file: Syntax error: Unexpected token 44 | 45 | type State<T_HT> = { > 46 | ghostHighlight: ?{ | ...

Navigational menu that slides or follows as you scroll

Wondering if anyone knows of a straightforward jQuery or Javascript method to create a navigation sidebar that smoothly moves with the user as they scroll down a page. A good example can be found here: Any suggestions would be greatly welcome. ...

An issue encountered with res.download() following res.render() in Node.js

Just started working with Node JS and ran into an issue: Error: Can't set headers after they are sent. I've checked my code, and the problem seems to be related to res.download(); Is there a way to display the view without using res.render()? ...

What steps can I take to ensure my CSS component remains unaffected by the global CSS styles?

My navbar component is not displaying the styles correctly as intended. I have a Navbar.module.css file to style it, but after using next-auth for social login, only the buttons remain unstyled while everything else gets styled. The code snippet for impor ...

Does setInterval consume a significant amount of CPU resources?

Recently, I came across an article stating that setInterval is considered to be CPU intensive. To verify this claim, I developed a script utilizing setInterval and closely monitored the CPU usage. Surprisingly, I did not observe any significant changes in ...

Looking to access the layout details of an HTML element similar to what can be done in Firefox's debugger tool?

I am facing a challenge with a aspx.net grid control where I need to extract the first row's information and copy it into another table using JavaScript. To achieve this, I am attempting to calculate the width of each cell in the first row by accessin ...

Solving the Issue of Assigning a Random Background Color to a Dynamically Created Button from a Selection of Colors

Trying to create my own personal website through Kirby CMS has been both challenging and rewarding. One of the features I'm working on is a navigation menu that dynamically adds buttons for new pages added to the site. What I really want is for each b ...

Tips for arranging div elements in a grid-like matrix layout

I am facing a challenge in arranging multiple rectangular divs into a grid structure with 10 columns and 10 rows. The CSS styles for the top, bottom, left, or right positions must be in percentages to accommodate zoom in and out functionality without overl ...

Build.js.erb requesting a partial script task

Struggling to make my create action function accurately in my rails app. The following two lines work as intended: $('#pit_form').remove(); //remove form $('#new_link').show(); //show new link again They successfully remove the form ...

Ten instances of $digest() being triggered upon the implementation of custom filters

I am struggling with the following angular markup: <tr ng-repeat="dia in dias"> <td>{{ dia[0].fecha }}</td> <td ng-repeat="bloque in bloques"> <div ng-repeat="hora in dia|soloBloque:bloque|sacarHoras"> ...

jQuery live function is not functioning as anticipated

I am facing issues with ajax requests and simple <input type="submit"/>. I have a practice of loading views within other views, in a modular way, using jQuery's .load(url) function to move from one view to another. The problem arises when I loa ...

Making sure to consistently utilize the service API each time the form control is reset within Angular 4

In the component below, an external API service is called within the ngOnInit function to retrieve an array of gifs stored in this.items. The issue arises when the applyGif function is triggered by a user clicking on an image. This function resets the For ...

The CORS problem arises only in production when using NextJS/ReactJS with Vercel, where the request is being blocked due to the absence of the 'Access-Control-Allow-Origin' header

I've encountered a CORS error while trying to call an API endpoint from a function. Strangely, the error only occurs in production on Vercel; everything works fine on localhost. The CORS error message: Access to fetch at 'https://myurl.com/api/p ...

Changing a class using JavaScript: Adding and removing class dynamics

Currently, I am attempting to create a function that will toggle the visibility of a visual object on and off whenever the user clicks on it. Additionally, I need to implement a click event listener within the HTML class named btn-sauce. Unfortunately, my ...