【问题标题】:Combine an object parameter with array values in Highcharts reduce method在Highcharts reduce方法中将对象参数与​​数组值组合
【发布时间】:2018-04-06 17:16:41
【问题描述】:

抱歉,由于英语不是我的第一语言,因此不知道如何准确搜索此内容。我想要做的是将数组值组合到一个对象参数。我正在使用 highcharts reduce 方法来显示单词的出现我的对象是obj{}

var data = Highcharts.reduce(series, function(arr, word) {
  var obj = Highcharts.find(arr, function(obj) {
    return obj.name === word;
  });
  obj = {
    name: word,
    weight: sortWeight()
  };
  arr.push(obj);
  console.log(obj);
  return arr;
}, []);

sortWeight 函数只是一个 for 循环

function sortWeight() {
            for (var i =0; i < sortedWeights.length; i++) {
                return sortedWeights [i];
            }
 }

我面临的问题是我总是使用这种策略得到的答案只是数组的第一个元素。 所以排序后的权重数组类似于sortedWeights =  [28, 17, 15, 15, 15, 12, 12, 11, 11, 10, 9, 8, 8, 8, 7, 7, 6, 6, 6, 6],但我的 Objectobj 的权重始终为 28,这是数组的第一个值。如何更改 weight 的值,使第二个单词的值是 17 第三个 15,依此类推。系列数组就像["great", "friendly", "good", "beautiful", "nice", "wonderful", "clean", "excellent", "helpful", "the best", "better", "comfortable", "front desk", "amazing", "perfect", "awesome", "amenities", "complaint", "gorgeous", "definitely stay"] 现在我想要得到的答案,即数据数组[{name:great, weight:28}, {name:friendly, weight:17}, {name:good, weight:15}, {name:beautiful, weight:15}....]

【问题讨论】:

  • sortWeight() 始终返回 1s 项 (28),并退出循环。
  • @OriDrori 是的,我知道,但您会建议修复吗?
  • 添加相关缺失数据(series),最终结果应该是什么。
  • @OriDrori 编辑了问题。结果是最后是我想要达到的..

标签: javascript arrays angularjs highcharts


【解决方案1】:

Array.map()迭代series,并使用索引(i)从sortedWeights获取匹配的号码:

var series = ["great", "friendly", "good", "beautiful", "nice", "wonderful", "clean", "excellent", "helpful", "the best", "better", "comfortable", "front desk", "amazing", "perfect", "awesome", "amenities", "complaint", "gorgeous", "definitely stay"];
var sortedWeights =  [28, 17, 15, 15, 15, 12, 12, 11, 11, 10, 9, 8, 8, 8, 7, 7, 6, 6, 6, 6];

var result = series.map(function(word, i) {
  return {
    name: word,
    weight: sortedWeights[i]
  };
});

console.log(result);

【讨论】:

    猜你喜欢
    • 2022-11-24
    • 2018-12-26
    • 2022-01-18
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多