Skip to content

Instantly share code, notes, and snippets.

@vamdt vamdt/five_num.js
Last active Aug 29, 2015

Embed
What would you like to do?
// 拿到嵌套数组的前五个
(function(){
var first_arr = [[1,3,4], [3,4,5,6,0], [34,56,23,56,34] [32,45]];// => [[1,3,4],[3,4]]
var second_arr = [[1,3,4,7], [3,4,5,6,0], [34,56,23,56,34] [32,45]]; // => [[1,3,4,7],[3]]
var third_arr = [[1,3,4,7,9], [3,4,5,6,0], [34,56,23,56,34] [32,45]]; // => [[1,3,4,7,9]]
var fourth_arr = [[1,3,4,7,9, 10], [3,4,5,6,0], [34,56,23,56,34] [32,45]]; // => [[1,3,4,7,9]]
function five(arr) {
var count = 0, result = [], left_count = 0;
for (var i = 0; i <= arr.length; i++) {
left_count = 5 - count;
if(count < 5 && arr[i].length <= left_count) {
result.push(arr[i]);
count += arr[i].length;
} else if (count < 5 && arr[i].length > left_count) {
result.push(arr[i].slice(0, left_count));
break;
} else {
break;
}
};
return result;
}
console.log( five(first_arr) );
console.log( five(second_arr) );
console.log( five(third_arr) );
console.log( five(fourth_arr) );
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.