Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

arrays - Javascript, repeating an object key N-times, being N its value

I was wondering how to do this in the more cleaner and optimal way:

I have an Object with the following structure:

{
   "125": 2,
   "439": 3,
   "560": 1,
   "999": 2,
   ...
}

I want to create a flat array repeating every key, the number of times indicated by its value. And bonus points for converting keys (strings) to integers. In this example, the resulting array should be:

[ 125, 125, 439, 439, 439, 560, 999, 999 ]

I've tried several ways but they all look over-engineered. For sure there is an easier way. This is what I've got with underscore (and it returns an Array of strings, nor integers):

_.compact(_.flatten(_.map(files, function(num, id) { 
     return new Array(num+1).join('$'+id).split('$') 
})))

I know there are plenty of ways to accomplish this. I just only want a clean and quick way. Being a Ruby developer it could be as easy as:

> files = {"125" => 2, "439" => 3, "560" => 1, "999" => 2}
 => {"125"=>2, "439"=>3, "560"=>1, "999"=>2} 
> files.map {|key, value| [key.to_i] * value}.flatten
 => [125, 125, 439, 439, 439, 560, 999, 999]

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I know this is plain JavaScript but seems cleaner to me than the code you posted:

var dict = {
   "125": 2,
   "439": 3,
   "560": 1,
   "999": 2
}
var result = [];

for(key in dict)
    for(i = 0; i < dict[key]; i++)
        result.push(key * 1);

alert(result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...