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

Capturing Data from Tables and Saving it with Protractor

Imagine having a table structured like this <h2>HTML Table</h2> <table> <tr> <th>Company</th> <th>Contact</th> <th>Code</th> </tr> <tr> <td>Alfreds Fu ...

The Lerna command for adding packages fails with an error message stating that the packages are not related

Currently, I am utilizing lerna to manage a multirepo containing interrelated packages. This issue only arose after installing a new operating system. Whenever I attempt to utilize lerna add to add a dependency from one package to another, an error occurs ...

Remove the JSON object by comparing IDs between two JSON objects in JavaScript or Node.js, deleting it if the ID is not found

let data = fetchData(); let anotherData = getAnotherData(); let result = data.reduce((accumulator, current) => { if (!accumulator[current.system.name]) { accumulator[current.system.name] = {}; } let detailsObject = {}; Object.keys(current. ...

Tips for managing errors when using .listen() in Express with Typescript

Currently in the process of transitioning my project to use Typescript. Previously, my code for launching Express in Node looked like this: server.listen(port, (error) => { if (error) throw error; console.info(`Ready on port ${port}`); }); However ...

AngularJS ng-repeat feature will display unique values in the list and filter out any duplicates, showing only distinct items

I am working on a piece of code that utilizes the ng-repeat directive to display the contents of a text box in a list. However, I have noticed that the code does not show duplicate letters. It only displays each letter once, even if they are repeated in th ...

Is there a different alternative to @JavascriptInterface in Android WebView?

I understand how to invoke a Java method within JavaScript code using the @JavascriptInterface annotation. However, I am facing an issue when trying to determine which JS method should be called from Android. Currently, I am triggering an Android Dialog ...

How to Update a Nested Document in Mongoose

I am currently working on a polls application using angular, express, and mongoose. Here is an overview of my data structure: var mongoose = require('mongoose'); var responseSchema = new mongoose.Schema({ responseText: String, votes: { ...

Is there a way to fix the error "The requested resource does not have the 'Access-Control-Allow-Origin' header" within Express using Firebase functions?

Trying to send an email through nodemailer using Firebase functions, but encountering errors. The data for the email will come from a form. Error message: Access to XMLHttpRequest at 'my-firebase-functions' from origin 'my-angular-web-app&a ...

I am looking to record my data by utilizing getInitialProps() in next.js

Being a beginner in next.js and react, I am eager to retrieve data from this particular free API link: The component index.js is as follows: import UserList from "./userList"; export default function Home() { return ( <div> &l ...

Preventing Broken URLs in Jquery each

What is the best way to prevent taking images with broken URLs? jQuery.each(jQuery('img'), function(index, obj) { imageStack.add(jQuery(obj)); }); ...

Concatenate a variable string with the JSON object key

I am currently working on a request with a JSON Object structure similar to the following: let formData = { name: classifierName, fire_positive_examples: { value: decodedPositiveExample, options: { filename: 'posit ...

Building a React.js application and fetching information with Ajax

In my quest to create a high-speed React.js application that functions as a game, I find myself in need of displaying real-time data. However, the traditional method of loading this data from the server using Ajax doesn't quite align with the reactive ...

What strategies can be used to manage Error return types in Typescript?

I have a situation where I need to handle either an object of type Person or an Error being returned by a function. My goal is to read the values of keys in the returned object only if it's not an Error. The code snippet below throws an error on the ...

Is there a way to recover a deleted element from an array?

I have a list of user cards, and my task is: Clicking the "undo" button: will restore the last card that was deleted (using an array) Question 1: How can I create an array from the displayed cards list? Question 2: How do I restore the last deleted card? ...

Send the film to Cloudinary from within an AngularJS single page application running within Electron

Currently, I am facing a challenge in my electron app which is an AngularJS SPA. I want to upload a file from the user's disk to Cloudinary directly from the front-end. In the past, I was successful in uploading photos from AngularJS by selecting the ...

Vue 2.0 custom filter not producing any output

I am attempting to create a customized filter that identifies and returns the items that correspond to a given input. It functions effectively with basic arrays like ['Apple', 'Banana', 'Cupple'], but encounters difficulty whe ...

Creating a Webgrid in MVC and integrating it with a custom class in AngularJS

Hey there, I'm a beginner when it comes to AngularJS and I'm looking to bind the webgrid within the method of AngularJS. $scope.SaveDetails = function () { debugger; var UserID = '@Session["ID"]'; ...

Executing the beforeRouteLeave navigation guard on a vue component for testing purposes

I am facing a challenge with unit testing the routing behavior of a vue component using jest. Specifically, when navigating away from the component, the 'beforeRouteLeave' guard in Vue-router is not triggering during testing, even though it works ...

The successful JSON response in an Ajax request is not functioning as expected

I've set up a data table that allows users to add rows by clicking the "plus" button. This triggers an ajax request to a URL with the rowId as a parameter (which corresponds to the specific row where the button was clicked). I expect to receive a JSON ...

Error with Ajax-bound selection (dropdown) - possibly due to an empty list in certain browsers

Upon taking over a project involving ASP.Net AJAX and JSON, I encountered an issue on a page that loads a large select (combo box) list of 1,430 entries. This list loads successfully on our main search page but produces an error in MicrosoftAjaxTemplates.d ...