0

In my SPFx web part below I get items from a list. That works fine.

What is the best way to randomise the results that come back?

I tried to do r = r.shuffle(); but I think I am way off.

Thanks P


        if(typeof this.properties.filterByPosition !='undefined' && this.properties.filterByPosition)
          camlQuery += "<And>";

        camlQuery += "<Eq><FieldRef Name='department'></FieldRef><Value Type='Text'>" + this.properties.groupName + "</Value></Eq>";

        if(typeof this.properties.filterByPosition !='undefined' && this.properties.filterByPosition)
          camlQuery += "<Eq><FieldRef Name='jobTitle'></FieldRef><Value Type='Text'>" + this.properties.filterByPosition + "</Value></Eq>";

        if(typeof this.properties.filterByPosition !='undefined' && this.properties.filterByPosition)
          camlQuery += "</And>";

        camlQuery += "</Where></Query></View>";



        //if(typeof this.properties.filterByPosition !='undefined' && this.properties.filterByPosition)

        const r = await sp.web.lists.getByTitle("UserData").getItemsByCAMLQuery({
          
            ViewXml: camlQuery,
        });
Pete Whelan
  • 85
  • 11

1 Answers1

0

Try using _.shuffle function available in lodash library.

For example:

const r = await sp.web.lists.getByTitle("UserData").getItemsByCAMLQuery({
    ViewXml: camlQuery,
}); 
const shuffledResponse: any = _.shuffle(r);

You can also find other methods for same at: How to randomize (shuffle) a JavaScript array?


You have to install lodash library using npm i lodash and then import it at the top of your file before using it:

import * as _ from 'lodash';
Ganesh Sanap
  • 1,386
  • 1
  • 8
  • 18
  • Thanks @Ganesh I did add lodash via npm. Now I get ... '_' refers to a UMD global, but the current file is a module. Consider adding an import instead. – Pete Whelan Oct 28 '22 at 14:43