我有两个json文件list1.json
和list2.json
,我设法将它们连接起来,但我有两个角色:
结果列表应该只包含list1.json
中的10个随机项,list2.json
中的所有项目,然后我应该在页面上以随机顺序显示它们。
我该怎么做?
答案 0 :(得分:1)
您可以使用lodash执行此任务。
_.sampleSize(list1.json, 10)
会给你十件随机物品,
那么_.concat(_.sampleSize(list1.json, 10), list2.json)
会给你想要的结果。
在您拥有包含所需项目的列表后,您可以使用_.shuffle
函数随机化其订单。
你可以在这里阅读更多内容: https://lodash.com/docs#sampleSize和https://lodash.com/docs#concat
当然,这两个函数都适用于JavaScript数组,而不是文件,你必须先阅读/需要这些文件并先解析它们。
答案 1 :(得分:0)
使用简单的javascript解决方案(但我建议使用下划线或Lodash,如Gilad Artzi所说)。
function array_random_idx(arr) {
var idx = parseInt(Math.random() * arr.length);
return idx;
}
function remove_random(arr) {
var idx = array_random_idx(arr);
return arr.splice(idx, 1)[0];
}
function array_shuffle(a) {
var j, x, i;
for (i = a.length; i; i -= 1) {
j = Math.floor(Math.random() * i);
x = a[i - 1];
a[i - 1] = a[j];
a[j] = x;
}
}
var result1 = []
for (var i = 0; i < 10; i++) {
var elem = remove_random(list1.json);
result1.push(elem);
}
var result = result1.concat(list2.json);
array_shuffle(result);
console.log(result);