我如何在LAMBDA Nodejs中随机播放数组?

我正在使用简单的lambda函数返回数组,但我需要对其进行洗牌,因此每次它都会正确更改序列。

dynamodb.scan(params, function(err, data) {
    if(err){
        console.log(err);
        callback(err);
    }
    else{

        console.log(data);
        const items = data.Items.map(
            (dataField) => {
                return {
                    rather:dataField.Rather.S, 
                    would:dataField.Would.S, 
                    wouldClick:+dataField.wouldClick.N, 
                    ratherClick:+dataField.ratherClick.N,
                    QuestionID:dataField.QuestionID.S, 


                };
            }    
        );
        callback(null, items);

    }

});

如您在回拨网站返回的项目中所看到的,我需要对这一项目进行洗牌,因此每个时间顺序都不相同,并且可以正确洗牌

项目的格式如下

[
  {
    "rather": "asd",
    "would": "dsa",
    "wouldClick": 4,
    "ratherClick": 2,
    "QuestionID": "f70da742-6731-48f4-84aa-a15c68e26cdf"
  },
  {
    "rather": "asda",
    "would": "ssam",
    "wouldClick": 4,
    "ratherClick": 1,
    "QuestionID": "de23902c-87ef-4a80-afd7-2f9b5bb0724d"
  },
  {
    "rather": "sada",
    "would": "asdk",
    "wouldClick": 2,
    "ratherClick": 3,
    "QuestionID": "7d57a847-b7e6-4e87-a9a4-abfe2a2d85ad"
  }
]
评论
毁灭
毁灭

您可以通过这种方式实施随机排序

const aa = [1,2,3,4,5,6,7,8]
const sortedRandomly = aa.sort(() => Math.random() - .5)

在您的情况下,尝试像这样实现您的代码

const items = data.Items.map(
            (dataField) => {
                return {
                    rather:dataField.Rather.S, 
                    would:dataField.Would.S, 
                    wouldClick:+dataField.wouldClick.N, 
                    ratherClick:+dataField.ratherClick.N,
                    QuestionID:dataField.QuestionID.S, 


                };
            }    
        ).sort(() => Math.random() - .5);
点赞
评论