您的位置:首页技术文章
文章详情页

javascript - 一个集合的元素均分给另一个数组对象, 有什么方法比较简便?

【字号: 日期:2023-11-24 13:38:06浏览:62作者:猪猪

问题描述

数组A=['G','D','B','H'] , 元素个数不定, 元素内容可以是任意字符

集合B=[{'id':'a',item:''},{'id':'a=b',item:''}], 数量不定, 结构固定

现在要把A中的元素均分给B中的item,分到多个时用逗号分隔.

对于A的元素个数小于或大于B的长度时, 只要求A要全部在B里出现就行了, 集合B的item至少要分到一个元素, 最好均分, 但集合B里的每个item不能有重复元素

有什么方法比较简便?

问题解答

回答1:

已经解决了

import com.google.common.collect.Lists;import com.google.common.collect.Maps;import com.google.common.collect.Sets;import org.apache.commons.collections.CollectionUtils;import org.apache.commons.lang3.RandomStringUtils;import org.apache.commons.lang3.RandomUtils;import org.apache.commons.lang3.StringUtils;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Set;/** * Created by YSTYLE on 2017-04-17 0017. */public class TEst { private static List<String> list = Lists.newArrayList(); private static List<Map> los = Lists.newArrayList(); public static void main(String[] args) {init();List<String> augmented = list;int groupCount = los.size();if (list.size() < groupCount){ augmented = Augmented(list, groupCount);}List<List<String>> chunk = chunk2(augmented, groupCount);for (int i = 0; i < los.size(); i++) { los.get(i).put('item', StringUtils.join(chunk.get(i),',') );}System.out.println(los); } // 初始化测试数据 private static void init (){int losCount = RandomUtils.nextInt(1,10);int listCount = RandomUtils.nextInt(1,10);for (int i = 0; i < listCount ; i++) { list.add(RandomStringUtils.randomAlphabetic(4));}for (int i = 0; i < losCount; i++) { Map<String,Integer> map = new HashMap<String, Integer>(); map.put('id',RandomUtils.nextInt(10000,99999)); los.add(map);}System.out.println('生成的数组: ' + list+' 数量: '+listCount);System.out.println('生成的对象数量: ' + los.size()); } // 分组数据 public static <T> List<List<T>> chunk2(List<T> list, int group){if (CollectionUtils.isEmpty(list)){ return Lists.newArrayList();}List<List<T>> result = Lists.newArrayList();Map<Integer,Set<T>> temp = Maps.newHashMap();for (int i = 0; i < list.size(); i++) { if (temp.containsKey(i%group)) {Set<T> ts = temp.get(i % group);ts.add(list.get(i));temp.put(i%group,ts); }else {Set<T> ts = Sets.newHashSet();ts.add(list.get(i));temp.put(i % group,ts); }}for (Set<T> ts : temp.values()) { result.add(Lists.newArrayList(ts));}return result; } // 填充数据 public static <T> List<T> Augmented(List<T> list ,int size){int length = CollectionUtils.isEmpty(list)?0:list.size();if (length<1){ return Lists.newArrayList();}List<T> result = Lists.newArrayList(list);if (length > size){ return result;}int count = size - length;for (int i = 0; i < count; i++) { result.add(list.get(RandomUtils.nextInt(0, length)));}return result; }}回答2:

1.A.length<=B.length 对A循环,直接赋值2.A.length>B.length对B循环let size = Math.floor(A.length/B.length)取整for(let i in B){数组划分 if(i==B.lenght-1){ B[i].item = A.splice(Start) }else{ let start = 0; B[i].item = A.splice(start,start + size)) start = start + 4; }}

标签: JavaScript