如果已预定义键

时间:2017-10-07 20:14:26

标签: javascript arrays algorithm

我有一些对象 - employeesArray,一个对象代表员工。假设一个对象具有以下结构:

{
   "name": "blabla", 
   "id": 1, 
   "position": {
      "code": "codeId", 
      "positionString": "CEO"
   }
}

我有另一个对象数组 - positionsArray,一个对象代表位置。假设一个对象具有以下结构:

{
   "code": "codeId", 
   "positionString": "CEO"
}

假设employeesArray有100名员工,positionsArray有15个职位。我想将positionsArray中存在的职位的员工提取到另一个数组中。

employee.position.code中必须存在

employee.position.positionStringpositionsArray

如何实现?

4 个答案:

答案 0 :(得分:0)

你可以使用Sets来有效地检查在positionArray中是否出现代码或位置字符串:



function findEmployees(employeesArray, positionsArray) {
    const codes = new Set(positionsArray.map( ({code}) => code )),
          positionStrings = new Set(positionsArray.map( ({positionString}) => positionString ));
    return employeesArray.filter( ({position: {code, positionString}}) => 
        codes.has(code) || positionStrings.has(positionString)
    );
}

// Sample data
var employeesArray = [{
   "name": "John", 
   "id": 1, 
   "position": {
      "code": "unknown",
      "positionString": "CEO"
   }
}, {
   "name": "Helen", 
   "id": 2, 
   "position": {
      "code": "9999",
      "positionString": "Deputy"
   }
}, {
   "name": "Joy", 
   "id": 3, 
   "position": {
      "code": "9876",
      "positionString": null
   }
}, {
   "name": "Vicky", 
   "id": 4, 
   "position": {
      "code": "8888",
      "positionString": "Director General"
   }
}, {
   "name": "Jack", 
   "id": 5, 
   "position": {
      "code": "0001",
      "positionString": "Clerk"
   }
}];

var positionsArray = [{
   "code": "0123", 
   "positionString": "CEO"
}, {
   "code": "9876", 
   "positionString": "Director"
}, {
   "code": "5555", 
   "positionString": "Head of Unit"
}]; 

console.log(findEmployees(employeesArray, positionsArray));

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:0)

步骤1:为positionArray中的每个元素创建一个循环 第2步:在循环体内部,使用filter命令过滤对象 第3步:将过滤后的员工放在另一个阵列中。

var result = [];
for (var i = 0; i < positionArray.length; i++) {
    var filteredEmployees = employeesArray.filter(function(emp){
        return emp.code == positionArray.code;
    });

    //Now put filtered employees into new array
    for (var t = 0; t < filteredEmployees.length; t++) {
       result.push(filteredEmployees[t]);
    }    
}

答案 2 :(得分:0)

使用Array.reduce一个人手头也有一个很好的工具......那么解决方案可能看起来像......

&#13;
&#13;
// Sample data
var employeesArray = [{
  "name": "John",
  "id": 1,
  "position": {
    "code": "unknown",
    "positionString": "CEO"
  }
}, {
  "name": "Helen",
  "id": 2,
  "position": {
    "code": "9999",
    "positionString": "Deputy"
  }
}, {
  "name": "Joy",
  "id": 3,
  "position": {
    "code": "9876",
    "positionString": null
  }
}, {
  "name": "Vicky",
  "id": 4,
  "position": {
    "code": "8888",
    "positionString": "Director General"
  }
}, {
  "name": "Jack",
  "id": 5,
  "position": {
    "code": "0001",
    "positionString": "Clerk"
  }
}];

var positionsArray = [{
  "code": "0123",
  "positionString": "CEO"
}, {
  "code": "9876",
  "positionString": "Director"
}, {
  "code": "5555",
  "positionString": "Head of Unit"
}];

var result = employeesArray.reduce(function (collector, employee) {
  if (collector.positions.some(collector.doesMatchBoundEmployee, employee)) {
    collector.employees.push(employee);
  }
  return collector;
}, {

  doesMatchBoundEmployee: function (position) {
    return (
         (position.code === this.position.code)
      || (position.positionString === this.position.positionString)
    );
  },
  positions: positionsArray,
  employees: []

}).employees;

console.log("result : ", result);
&#13;
.as-console-wrapper { max-height: 100%!important; top: 0; }
&#13;
&#13;
&#13;

答案 3 :(得分:0)

这是功能风格的另一种解决方案:

// Sample data
const employeesArray = [
  { "name": "John", "id": 1, "position": { "code": "unknown", "positionString": "CEO" } },
  { "name": "Helen", "id": 2, "position": { "code": "9999", "positionString": "Manager" } },
  { "name": "Joy","id": 3, "position": { "code": "9876", "positionString": "Manager" } },
  { "name": "Vicky", "id": 4, "position": { "code": "8888", "positionString": "Director" } },
  { "name": "Jack", "id": 5, "position": { "code": "0001", "positionString": "Manager" } }
]

const positionsArray = [
  { "code": "0123", "positionString": "CEO" },
  { "code": "9876", "positionString": "Director" },
  { "code": "5555", "positionString": "Manager" }
]

// we are going to step through the positions array
// and examine positionsArray.positionString
// and produce an object that has one property for each position
const extractPositions = positionsArray.reduce((all, position) => {
  // set the position to a variable
  const title = position.positionString
  // now we are going to filter out every user that has the title
  // and set the result of that to the title property on the object we are creating
  all[title] = employeesArray.filter((e) => e.position.positionString === title)
  // return all is needed because we are accumulating the results
  return all
}, {}) // {} is where we define we are creating an object,
       // and 'return all' adds to it every iteration

console.log('CEO', extractPositions.CEO)
console.log('Director', extractPositions.Director)
console.log('Manager', extractPositions.Manager)

以下是它看起来变成一个你可以通过传入两个数组调用的函数:

const sortPositions = (positions, employees) => {
  const final = positions.reduce((all, position) => {
    const title = position.positionString
    all[title] = employees.filter((e) => e.position.positionString === title)
    return all
  }, {})
  return final
}

console.log(sortPositions(positionsArray, employeesArray))

而且,这是非常神秘的,最终浓缩版本:

const getEmployees = (positions, employees) =>
  positions.reduce((all, position) => {
    all[position.positionString] = employees.filter((e) =>
      e.position.positionString === position.positionString)
    return all
  }, {})

console.log(getEmployees(positionsArray, employeesArray))

我会选择我的3个例子中的第二个,因为第三个例子,虽然更加精简会让你在6个月后再次回到代码时讨厌生活。第二个没有使用implicit returns,它也更明确地帮助人理解title在逻辑中是重要的。

我们在这里做的基础是有两个数组,我们需要以某种方式将它们相互比较,所以在我的例子中,我们决定使用positions数组作为字典,我们创建一个员工列表在字典中找到每个标题。

如果没有字典或标题的员工不在字典中,则忽略它们。

如果标题中有0名员工,则会在最终结果中添加一个空数组。

如果我们想要捕获unsorted员工会变得更加复杂,但为了做到这一点,您可能希望在您的职能中保存employees数据的副本,并删除每个员工找到。新数组中的任何剩余员工将被添加到最终结果中的未排序数组中。这将在最后一次通过reduce函数时完成。在解释它时,这不会是微不足道的,但它只会增加大约5-10行代码。

以下是reduce如何工作的示例,因为我认为它是一个非常有用的工具。它是一个累加器,所以它就像一个迭代器(forEach,map),但它允许你随时累积结果,这样你就可以构建一个和,数组或对象。

const numbers = [1, 3, 5, 7, 9]

const addNumbers = numbers.reduce((all, item, i) => {
  console.log('\nAll is currently:', all)
  console.log('We are currently looking at:', item)
  console.log('Current index position:', i)
  all = all + item
  return all
}, 0)

console.log('\nThe total is:', addNumbers)

查看0处的}, 0)。如果将其更改为[]{},则构建数组或对象而不是总计。如果你做[],你可以在内部缩小:all.push('anything'),如果你做{},你可以all.prop = 'anything'(或我们all[title]使用括号表示法创建动态属性名称。

它变得insanely强大,因为您可以执行{}而不仅仅是{ good: [], bad: [] },它允许您创建非常复杂的对象。每个循环遍历原始数组中的每个项目,您可以说if (something === 'good') all.good.push(item)等,并构建一个具有超复杂属性的对象,并且您只需要将原始数组传递一次。 / p>