Javascript .根据投票数将对象标题数组映射到新数组中
我有一个像这样的对象数组Javascript .根据投票数将对象标题数组映射到新数组中,javascript,arrays,reactjs,object,array.prototype.map,Javascript,Arrays,Reactjs,Object,Array.prototype.map,我有一个像这样的对象数组 array = [ { title: Title1, votes: 2, }, { title: Title2, votes: 1, }, { title: Title3, votes: 1, }, ]; newArray = [Title1, Title1, Title2, Title3] 我想做的是使用.map将标题推送到一个新数组中,但要基于对象的投票数 对于这个例子,它看起来像这样 ar
array = [
{
title: Title1,
votes: 2,
},
{
title: Title2,
votes: 1,
},
{
title: Title3,
votes: 1,
},
];
newArray = [Title1, Title1, Title2, Title3]
我想做的是使用.map将标题推送到一个新数组中,但要基于对象的投票数
对于这个例子,它看起来像这样
array = [
{
title: Title1,
votes: 2,
},
{
title: Title2,
votes: 1,
},
{
title: Title3,
votes: 1,
},
];
newArray = [Title1, Title1, Title2, Title3]
在我使用React时,使用.map是最好的方法。您可以将
map
与concat
方法和扩展语法结合使用
let数组=[{title:'Title1',投票数:2},{title:'Title2',投票数:1},{title:'Title3',投票数:1}];
让result=[].concat(…array.map({title,voates})=>array(voates.fill(title));
console.log(result)
您可以通过将投票数
作为按下标题的while循环的计数来减少数组
var数组=[{title:'Title1',投票数:2},{title:'Title2',投票数:1},{title:'Title3',投票数:1}],
result=array.reduce((r,{title,vots})=>{
而(投票)r.push(标题),;
返回r;
}, []);
控制台日志(结果)代码>不,这不是最好的。当需要与原始数组长度相同的新数组时,此选项非常有用。您可以通过以下方式实现您的目标:
const数组=[{title:'Title1',投票数:2},{title:'Title2',投票数:1},{title:'Title3',投票数:1}];
const result=array.reduce((res,el)=>res.concat(array(el.vots).fill(el.title)),[]);
控制台日志(结果)
Array.map
每个元素只返回一个值。您可能需要类似于数组的内容。减少:
let newArray = array.reduce((accum, curValue) => {
for (let i = 0; i < curValue.votes; i++) {
accum.push(curValue.title);
}
return accum;
}, []);
让newArray=array.reduce((累计,曲线值)=>{
for(设i=0;i
您可以将“地图”、“填充”和“混凝土”组合在一起,如下所示:
Array.prototype.concat(...array.map(elem => new Array(elem.votes).fill(elem.title)))
结果
["Title1", "Title1", "Title2", "Title3"]
我将首先使用array.sort()然后使用array.map()只返回所需的属性,如下所示(原始数组保持不变,没有变化):
票数相同的标题按字母顺序排列。谢谢,这正是我想要做的。谢谢你提供的关于附加数组函数的信息,我必须检查一下。