rearrange results in ng-repeat based on specified array in AngularJS

Currently delving into Angularjs and have a quick query:

I recently received an array from a user which looks like this:

userPreferences = [7,5,4]

Additionally, I am working with an object that uses ng-repeat to showcase various news items. The object structure is as follows:

{
    "id": 1,
    "preferences": [
      3,
      4
    ]
}

My goal is to utilize the array retrieved from user preferences within my ng-repeat function in order to sort the news articles by displaying the preferred ones first, followed by the remaining news. Is this achievable?

Would something along these lines work:

<li ng-repeat="new in news | filter:{'userPreferences' : new.preferences}">

I'm not entirely sure whether I should be using filter, orderBy, or sort for this task. Any assistance would be greatly appreciated!

Answer №1

If you want to create a custom function that calculates the number of matched preferences in your scope, you can do so like this:

function findMatchingPreferences(array1, array2) {
    return $filter('filter')(array1, function(n){
    return array2.indexOf(n) != -1;
  });
}

$scope.countMatchedPreferences = function(n) {
    return findMatchingPreferences(n.preferences, $scope.userPreferences).length;
};

You can then use this function with the orderBy filter like this:

<li ng-repeat="n in news | orderBy:countMatchedPreferences:true">{{n}}</li>

This will sort the news items based on the number of matched preferences in descending order.

Check out the example on Fiddle

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

Creating a search-enabled multi-select feature in a Tabulator.js column

Currently, I am working on a project involving Tabulator.js and attempting to incorporate a column with a multi-select feature that includes a search option. My approach has been to utilize the Select2 library, but I have run into some challenges. Here is ...

Connect two ng-models in a select in AngularJS

Is it possible to bind two ng-models in a select tag? Let me explain with some code snippets. I have a set of dynamic input buttons that allow users to add new options. Each option has properties opt.id and opt.text. <div ng-repeat="opt in q.options"& ...

Transform HTML content into a PDF document with page breaks

Currently, I am developing a function that involves an HTML template. The purpose of this function is to generate a dynamic template and convert it into a PDF. So far, I have been able to achieve this using the following code: var output = ''; ...

Manipulating a global variable in VueJS

Currently, I am referring to Global data with VueJs 2 for my project, focusing on only one variable. In the code provided, I have included an @click event to update the variable. However, it throws an error stating "Uncaught ReferenceError: $myGlobalStuff ...

"VS Code's word wrap feature is beneficial for wrapping long lines of text and code, preventing them from breaking and ensuring they are

text not aligning properly and causing unnecessary line breaks insert image here I attempted to toggle the word wrap feature, installed the Rewrap plugin, and played around with vscode settings ...

Developing dynamic checkbox components using jQuery - unusual behavior in Internet Explorer

I am dynamically creating checkbox elements using jQuery and appending them to a specified node as shown below var topics = ['All','Cat1','Cat2']; var topicContainer = $('ul#someElementId'); $.each( topics, functio ...

Why do we even need Angular controllers when directives can perform the same tasks as controllers?

As a new Angular developer, I have to say that I am really impressed with the architecture of this framework. However, one thing that puzzles me is the existence of controllers. Let me elaborate: Services in Angular seem to have a clear purpose: 1) Store ...

Tips for displaying error messages directly next to input fields in a service portal

I'm attempting to display an error message next to my input field g_form.showFieldMsg('request_type','Low impact not allowed with High priority','error'); It's working well. Now, I would like to include a link in ...

creating a multi-tiered dropdown menu using both CSS and JavaScript

I am in need of a multi-level (drop down) menu feature, that allows me to make changes to the menu in just one file, without having to navigate through each individual page. I require a three level menu. I have attempted to modify someone else's code ...

Refreshing a Vue JS component

As a beginner in VueJs, I am facing an issue with reloading a component and table when a refresh button is clicked. I have tried using the forceUpdate method and changing keys, but it has not been successful so far. If anyone has any suggestions on how to ...

Retrieve information from the database and showcase it in a competitive ranking system

Here is the HTML and CSS code for a leaderboard: /* CSS code for the leaderboard */ To display the top 5 in the leaderboard, PHP can be used to fetch data from the database: <?php // PHP code to retrieve data from the database ?> The current ou ...

Inactive user registration with activation through OTP

Here is the process for the authentication flow: The user registers by entering his details and receives an OTP via email. Upon registration, the user's details are stored in mongoDB. In this case, the user can login to the application before valida ...

How can you efficiently identify and resolve coding errors or typos in your code?

While practicing node.js and express.js, I encountered an issue with finding typos. One such instance was when I mistakenly typed: const decoded = jwt.veryfy(token, config.get('jwtSecret')); instead of jwt.verify. Even though I eventually disc ...

Effortlessly move and rearrange various rows within an HTML table by utilizing JQuery alongside the <thead> elements

My JsFiddle has two tables and I want to switch rows <tr> between them using Jquery. However, due to the presence of the <thead> tag, it is not functioning properly. I suspect that the issue lies with the items in the selector, but I am unsure ...

Dealing with Superagent and Fetch promises - Tips for managing them

Apologies for posing a question that may be simple for more seasoned JS programmers. I've been delving into superagent and fetch to make REST calls, as I successfully implemented odata but now need REST functionality. However, I'm facing confusio ...

Ways to extract a single digit from the total sum of a date in the format of 15-06-2015

Is there a way to extract a single digit from the sum of a number in date format, such as 15-06-2015? My goal is to convert the date format 15-06-2015 into a single-digit value by adding up the numbers. For instance: In the case of 15-05-2015, the output ...

Tips for executing a script while updating npm version

Can a script be executed during the npm version command, after the release number has been incremented but before the git tag is created and pushed? ...

Experimenting with an angularjs directive, not yielding the desired results

Trying to use a directive here, and all the resources I've found online seem to be a variation of what I have. Here is the directive I created: angular.module('App'); App.directive("scrollBottom", ["$interval", function ($interval) { retu ...

What is the best way to enter text into the terminal following the execution of "yarn start"?

While developing a Node chat application, I encountered an issue where I am unable to type anything in the terminal after entering "yarn start". The tutorial I am following shows that the instructor can still input commands in their terminal after running ...

Utilize store functions (such as dispatch and getState) in external modules like webSockets, rather than within components

I have implemented React and Redux, along with webSocket to handle server side events. Currently, I can dispatch actions from a component by assigning a function to the dispatcher using the mapDispatchToProps() function. But what if I want to trigger an ...