Javascript 使用';减少';操纵对象并生成数组的步骤
我知道reduce在Javascript中是一个非常强大的数组方法,并且已经看过很多示例,但无法使用它来完成下面的任务 按年龄对人员统计对象进行分组,其中年龄差异不得大于5,每组最多只能有3人 我已经能够用下面的代码实现它Javascript 使用';减少';操纵对象并生成数组的步骤,javascript,typescript,ecmascript-6,mapreduce,reduce,Javascript,Typescript,Ecmascript 6,Mapreduce,Reduce,我知道reduce在Javascript中是一个非常强大的数组方法,并且已经看过很多示例,但无法使用它来完成下面的任务 按年龄对人员统计对象进行分组,其中年龄差异不得大于5,每组最多只能有3人 我已经能够用下面的代码实现它 const immutable = require('../fixtures/inputs/input') const edge = require('../fixtures/inputs/edge-input') /** * This is the entry point
const immutable = require('../fixtures/inputs/input')
const edge = require('../fixtures/inputs/edge-input')
/**
* This is the entry point to the program
*
* @param {any} input Array of student objects
*/
function classifier(input) {
// console.log(input)
// let returnedInput = []
let newInput = JSON.parse(JSON.stringify(input));
let exampleOutput = {
}
if (!Array.isArray(newInput)) {
throw new Error("invalid")
}
if (newInput.length < 1) {
exampleOutput = { noOfGroups: 0 }
}
function compare(a, b) {
const { age: ageA, regNo: regNoA } = a
const { age: ageB, regNo: regNoB } = b
// const ageA = a.age
// const ageB = b.age
let comparison = 0;
if (ageA > ageB) {
comparison = 1;
} else if (ageA < ageB) {
comparison = -1;
}
return comparison
}
const ages = newInput.map(function (each) {
let datDob = new Date(each.dob).getFullYear()
return each.age = new Date().getFullYear() - datDob
})
sortedInput = newInput.sort(compare)
// console.log(sortedInput)
const getMember = (arg) => {
let memArray = []
// console.log(arg)
if (arg.length == 1) {
return arg
}
let i = 0;
let j = 1;
// console.log(arg)
// console.log(arg.length)
while (i <= arg.length) {
while (j < 3) {
// console.log(arg[j])
if (arg[j]) {
if ((arg[j].age - arg[i].age) <= 5) {
memArray.push(arg[j])
}
}
j++
}
memArray.push(arg[i])
i++
return memArray
}
}
let i = 0;
// console.log(sortedInput)
while (sortedInput.length >= 1) {
// console.log(sortedInput)
let memberss = getMember(sortedInput)
memberss = memberss.sort(compare)
// let memRegSort = memberss.sort((a, b) => (a.regNo > b.regNo) ? 1 : -1)
memberss = memberss.sort((a, b) => (a.age > b.age) ? 1 : (a.age === b.age) ? ((a.regNo > b.regNo) ? 1 : -1) : -1)
// return memberss
const oldest = memberss.map(item => item.age).reduce((a, b) => Math.max(a, b))
const sumAge = memberss.map(item => item.age).reduce((total, curVal) => total + curVal)
const regNo = memberss.map(item => parseInt(item.regNo))
exampleOutput[`noOfGroups`] = i + 1
exampleOutput[`group${i + 1}`] = {}
exampleOutput[`group${i + 1}`]['members'] = memberss
exampleOutput[`group${i + 1}`].oldest = oldest
exampleOutput[`group${i + 1}`].sum = sumAge
exampleOutput[`group${i + 1}`].regNos = regNo.sort((a, b) => a > b ? 1 : -1)
sortedInput = sortedInput.slice(memberss.length, sortedInput.length + 1)
// console.log(sortedInput)
// sortedInput.splice(0, memberss.length)
// console.log(exampleOutput[`group${i + 1}`]['members'])
i++
}
// console.log(exampleOutput)
return exampleOutput
// console.log (getMember(sortedInput))
}
const input = [
{
name: 'Hendrick',
dob: '1853-07-18T00:00:00.000Z',
regNo: '041',
}
]
Object.freeze(edge)
const out = classifier(edge)
console.log(out)
module.exports = classifier;
function classifier(input) {
let newInput = JSON.parse(JSON.stringify(input));
let exampleOutput = {
noOfGroups:0,
group: {
member: [],
oldest: 0,
regNos: []
}
}
if (!Array.isArray(newInput)) {
throw new Error("invalid")
}
if (newInput.length < 1) {
exampleOutput = { noOfGroups: 0 }
}
function compare(a, b) {
const { age: ageA } = a
const { age: ageB } = b
return ageA-ageB
}
const ages = newInput.map(function (each) {
let datDob = new Date(each.dob).getFullYear()
return each.age = new Date().getFullYear() - datDob
})
sortedInput = newInput.sort(compare)
const member = (arr)=>{
let result = []
return arr.length < 1 ? { noOfGroups: 0} :
arr.reduce((acc, cur, index, arr) => {
index= index-1
let num = 0
// console.log(cur.age)
let item = arr.findIndex(item => item.age +5 >= cur.age)
item == 0 ? result.push(cur) : result
result.length > 3 ? result.pop() : result
num = num+1
acc.noOfGroups = num
acc[`group${num}`] = {}
acc[`group${num}`].members = []
acc[`group${num}`].members.push(result)
acc[`group${num}`].oldest = result.map(item => item.age).reduce((a, b) => Math.max(a, b))
acc[`group${num}`].regNos = result.map(item => item.age)
// console.log(arr.slice)
index = index-1
return index < 0 ? member(arr.slice(acc[`group${num}`].regNos.length, 16)) : acc
return acc
}, [{noOfGroups: 0}, ])
}
return member(sortedInput)
return exampleOutput
}
输出
如何使用reduce实现同样的功能。
我试过下面的代码
const immutable = require('../fixtures/inputs/input')
const edge = require('../fixtures/inputs/edge-input')
/**
* This is the entry point to the program
*
* @param {any} input Array of student objects
*/
function classifier(input) {
// console.log(input)
// let returnedInput = []
let newInput = JSON.parse(JSON.stringify(input));
let exampleOutput = {
}
if (!Array.isArray(newInput)) {
throw new Error("invalid")
}
if (newInput.length < 1) {
exampleOutput = { noOfGroups: 0 }
}
function compare(a, b) {
const { age: ageA, regNo: regNoA } = a
const { age: ageB, regNo: regNoB } = b
// const ageA = a.age
// const ageB = b.age
let comparison = 0;
if (ageA > ageB) {
comparison = 1;
} else if (ageA < ageB) {
comparison = -1;
}
return comparison
}
const ages = newInput.map(function (each) {
let datDob = new Date(each.dob).getFullYear()
return each.age = new Date().getFullYear() - datDob
})
sortedInput = newInput.sort(compare)
// console.log(sortedInput)
const getMember = (arg) => {
let memArray = []
// console.log(arg)
if (arg.length == 1) {
return arg
}
let i = 0;
let j = 1;
// console.log(arg)
// console.log(arg.length)
while (i <= arg.length) {
while (j < 3) {
// console.log(arg[j])
if (arg[j]) {
if ((arg[j].age - arg[i].age) <= 5) {
memArray.push(arg[j])
}
}
j++
}
memArray.push(arg[i])
i++
return memArray
}
}
let i = 0;
// console.log(sortedInput)
while (sortedInput.length >= 1) {
// console.log(sortedInput)
let memberss = getMember(sortedInput)
memberss = memberss.sort(compare)
// let memRegSort = memberss.sort((a, b) => (a.regNo > b.regNo) ? 1 : -1)
memberss = memberss.sort((a, b) => (a.age > b.age) ? 1 : (a.age === b.age) ? ((a.regNo > b.regNo) ? 1 : -1) : -1)
// return memberss
const oldest = memberss.map(item => item.age).reduce((a, b) => Math.max(a, b))
const sumAge = memberss.map(item => item.age).reduce((total, curVal) => total + curVal)
const regNo = memberss.map(item => parseInt(item.regNo))
exampleOutput[`noOfGroups`] = i + 1
exampleOutput[`group${i + 1}`] = {}
exampleOutput[`group${i + 1}`]['members'] = memberss
exampleOutput[`group${i + 1}`].oldest = oldest
exampleOutput[`group${i + 1}`].sum = sumAge
exampleOutput[`group${i + 1}`].regNos = regNo.sort((a, b) => a > b ? 1 : -1)
sortedInput = sortedInput.slice(memberss.length, sortedInput.length + 1)
// console.log(sortedInput)
// sortedInput.splice(0, memberss.length)
// console.log(exampleOutput[`group${i + 1}`]['members'])
i++
}
// console.log(exampleOutput)
return exampleOutput
// console.log (getMember(sortedInput))
}
const input = [
{
name: 'Hendrick',
dob: '1853-07-18T00:00:00.000Z',
regNo: '041',
}
]
Object.freeze(edge)
const out = classifier(edge)
console.log(out)
module.exports = classifier;
function classifier(input) {
let newInput = JSON.parse(JSON.stringify(input));
let exampleOutput = {
noOfGroups:0,
group: {
member: [],
oldest: 0,
regNos: []
}
}
if (!Array.isArray(newInput)) {
throw new Error("invalid")
}
if (newInput.length < 1) {
exampleOutput = { noOfGroups: 0 }
}
function compare(a, b) {
const { age: ageA } = a
const { age: ageB } = b
return ageA-ageB
}
const ages = newInput.map(function (each) {
let datDob = new Date(each.dob).getFullYear()
return each.age = new Date().getFullYear() - datDob
})
sortedInput = newInput.sort(compare)
const member = (arr)=>{
let result = []
return arr.length < 1 ? { noOfGroups: 0} :
arr.reduce((acc, cur, index, arr) => {
index= index-1
let num = 0
// console.log(cur.age)
let item = arr.findIndex(item => item.age +5 >= cur.age)
item == 0 ? result.push(cur) : result
result.length > 3 ? result.pop() : result
num = num+1
acc.noOfGroups = num
acc[`group${num}`] = {}
acc[`group${num}`].members = []
acc[`group${num}`].members.push(result)
acc[`group${num}`].oldest = result.map(item => item.age).reduce((a, b) => Math.max(a, b))
acc[`group${num}`].regNos = result.map(item => item.age)
// console.log(arr.slice)
index = index-1
return index < 0 ? member(arr.slice(acc[`group${num}`].regNos.length, 16)) : acc
return acc
}, [{noOfGroups: 0}, ])
}
return member(sortedInput)
return exampleOutput
}
我是这样做的:
dob
计算年龄总和
、最早的
,以及其他属性。如果没有,我们将使用当前成员创建一个新组const input=[{name:'Hendrick',dob:'1853-07-18T00:00:00.000Z',regNo:'041',},{name:'Albert',dob:'1910-03-14T00:00:00.000Z',regNo:'033',},{name:'Marie',dob:'1953-11-07T00:00.000Z',regNo:'024',},{name:'Neils',dob:'1853-10-07T00:00.000Z',regNo:'02',{name:'Max',dob:'1853-04-23T00:00:00.000Z',regNo:'014',},{name:'Erwin',dob:'1854-08-12T00:00:00.000Z',regNo:'09',},{name:'Auguste',dob:'1854-01-28500:00:00.000Z',regNo:'08',},{name:'Karl dob:'1852-12-05T00:00.000Z',regNo:'120',name:'1852-08-08:00:00,},{路易regNo:'020,{姓名:'Arthur',dob:'1892-09-10T00:00:00.000Z',regNo:'321',},{姓名:'Paul',dob:'1902-08-08T00:00:00.000Z',regNo:'055',},{姓名:'William',dob:'1890-03-31T00:00:00.000Z',regNo:'013',},{姓名:'Owen dob:'1853-04-26T00:00.000Z',regNo:'052',姓名:'Martin',dob:'15T00:00',regNo:',{姓名:'Guye',出生日期:'1854-10-15T00:00:00.000Z',注册号:'084',},{姓名:'Charles',出生日期:'1954-02-14T00:00:00.000Z',注册号:'091',},];
//根据出生日期计算年龄。
const data=input.map(项=>{
让年龄=新日期().getFullYear()-新日期(item.dob).getFullYear();
返回{…项,年龄};
});
var结果=数据减少((会计科目,当前)=>{
让group=Object.values(acc).find(group=>group.members&&group.members.length<3
&&group.members.every(member=>Math.abs(member.age-curr.age)<5));
国际单项体育联合会(小组){
组.成员.推送(curr);
分组规则推送(当前规则);
group.oldest=Math.max(…group.members.map(member=>member.age));
group.sum=group.sum+curr.age;
}否则{
acc.noOfGroups=acc.noOfGroups+1 | | 1;
让groupName=“group”+acc.noOfGroups;
acc[groupName]={
“成员”:[当前],
“最古老的”:当代,
“总和”:货币,
“注册号”:[当前注册号],
};
}
返回acc;
}, {});
console.log(result);
我首先使用(免责声明:我是它的作者之一)编写了此代码:
const transform=pipe(
地图(地址),
sortBy(道具(‘年龄’),
makegroup(doesItFit),
姓名组,
地图(施工组)
)
通过附加的帮助函数,addAge
,makeGroups
,doesItFit
,nameGroups
,以及constructObj)
。我非常喜欢这种逐步转换输出的风格
但是Ramda只是一个助手函数的集合(当然,它的设计允许某种特定的编码风格),我们自己编写这些函数的版本很容易
但是把这样的功能
constpipe=(…fns)=>(arg)=>
fns.reduce((o,f)=>f(o),arg)
在我们自己的实用程序库中,我们可以相对容易地构建如上所述的干净代码
对于本例,我最终使用了许多Ramda函数,以及可能属于这样一个库的两个助手(numericSort
和makeGroups
),但这些函数很容易为我们自己编写,我们可以在它们的基础上构建此函数
//实用程序函数
常量管道=(…fns)=>(arg)=>
fns.reduce((o,f)=>f(o),arg)
常量映射=(fn)=>(xs)=>
映射(x=>fn(x))
常量排序=(比较器)=>(xs)=>
排序(比较器)
常量numericSort=排序((a,b)=>a-b)
常量排序=(fn)=>(xs)=>
排序((a,b,x=fn(a),y=fn(b))=>xy-1:0)
常量和=(xs)=>
x.reduce((a,b)=>a+b,0)
常量属性=(名称)=>(对象)=>
obj[名称]
常量弹拨=(道具)=>(xs)=>
map(x=>x[prop])
常量映射对象=(fn)=>(obj)=>
Object.assign(…Object.entries(obj.map)([k,v])=>({[k]:fn(v)})))
常量makeGroups=(测试)=>(xs)=>
xs.reduce((组,x)=>{
const idx=groups.findIndex(g=>test(g,x))
返回idx>-1
?[…groups.slice(0,idx),[…groups[idx],x],…groups.slice(idx+1)]
:[…组,[x]]
}, [])
//助手
常量地址=({dob,…rest})=>
({…rest,dob,age:new Date().getFullYear()-new Date(dob.getFullYear()})
const nameGroups=组=>
reduce((i=>(a,g)=>({…a,[`group${i++}`]:g}))(1),{})
const doesItFit=(组、项)=>
group.length<3&&group.every(x=>Math.abs(x.age-item.age)<5)
const constructGroup=(组)=>({
成员:小组,
//成员:JSON.stringify(集团),
年龄最大的:Math.max(…Pull('age')(组)),
sum:sum(拔毛(‘年龄’)(组)),
regNos:numericSort(map(Number)(pull('regNo')(group)),
})
//主要功能
常量转换=管道(
地图(地址),
sortBy(道具(‘年龄’),
makegroup(doesItFit),
姓名组,
mapObject(构造组)
)
//示范
const input=[{name:“Hendrick”,dob:“1853-07-18T00:00:00.000Z”,regNo:“041”},{name:“Albert”,dob:“1910-03-14T00:00:00.000Z”,regNo:“033”},{name:“Marie”,dob:“1953-11-07T00:00:00.000Z”,regNo:“024”},{name:“Neils”,dob:“1853-10-07T00:00:00.000Z”,regNo:“02”{name:“Max”,dob:“1953-11-07T00:00:00,{,dob:“1854-08-12T00:00:00.0
{ noOfGroups: 1,
group1: { members: [ [Array] ], oldest: 66, regNos: [ 65, 66 ] } }