如何在Javascript中从另一个数组中排序数组?

时间:2018-01-25 02:00:11

标签: javascript html arrays lodash

我在模块中创建了两个数组。这已插入下面。

var a = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
var b = [{name:"Fri", value:10}, {name:"Thu", value:5}];

我的要求是我想要创建另一个数组顺序的数组" a"。如果名称不包含在" b"数组,我需要将值0推入一个新数组。

预期结果,

var result = [0, 0, 0, 5, 10, 0, 0];

我的代码,

const result= [];
    _.map(a, (el, i) => {
      if(b[i] !== undefined) {
        if(el === b[i].name) {
          result.push(b[i].value);
        } else {
          result.push(0);
        }
      }
    });

2 个答案:

答案 0 :(得分:2)

Array#find()在这里很有用

var a = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
var b = [{name:"Fri", value:10}, {name:"Thu", value:5}];

var res = a.map(s => {
  var bMatch = b.find(o => o.name === s);// returns found object or undefined
  return bMatch ? bMatch.value : 0;
});

console.log(JSON.stringify(res))

答案 1 :(得分:1)

您需要通过遍历b的所有元素来查找b内的值,以了解它是否存在。

我建议将b的结构调整为:

var b = {
  "Fri": 10,
  "Thu": 5,
}

如果这不是一个选项,那么您可以使用当前结构来实现这一目标:

var a = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
var b = [{name:"Fri", value:10}, {name:"Thu", value:5}];

const result = a.map((aVal) => {
    var found = 0; // default to 0 if not found
    // edit: this iteration could be replaced with find in the other answer
    b.forEach((bVal) => { // try to find the day in b
       if (bVal.name === aVal) { // if the day is found 
          found = bVal.value; // set the found value to value field of b element
       }
    });
    return found;
 });

 console.log(result);