#数组
a = ["12","34","56","56"]
#去重
a = a.uniq
#a = ["12","34","56"]
var arr = [
{name: 'aa',age: 1},
{name: 'bb',age: 1},
{name: 'cc',age: 1},
{name: 'cc',age: 1},
{name: 'cc',age: 1},
{name: 'dd',age: 1},
{name: 'dd',age: 1},
{name: 'cc',age: 1},
{name: 'cc',age: 1},
{name: 'dd',age: 1},
{name: 'dd',age: 1},
{name: 'e',age: 1},
{name: 'e',age: 1},
{name: 'dd',age: 1},
];
//添加属性number:次数
arr.forEach(tem => {
tem.number = 1;
});
//去重,并添加次数
for (var i = 0;i < arr.length; i++){
for (var j = i+1;j < arr.length;j++){
if (arr[i].name == arr[j].name){
arr.splice(j,1);
j--;
arr[i].number++;
}
}
}
需要实现这样的函数:
对指定的数组进行分析,打印出某个元素出现的次数。 (提示:使用hash)
print_occur_times(my_array) 例如: my_array = [1,2,3,3,3,4,4,5,5,5,5,5,5,8,9,9] print_occur_times(my_array) 结果: 1: 1 # 1出现1次 2: 1 # 2出现1次 3: 3 # 3出现3次 4: 2 $ 4出现2次。 5: 6 8: 1
my_array = [1,2,3,3,3,4,4,5,5,5,5,5,5,8,9,9]
print_occur_times(my_array)
def print_occur_times some_array
temp = {}
for i in some_array
#puts i
if temp[i] != nil
temp[i] = temp[i] + 1
else
temp[i] = 1
end
end
puts temp
end
my_array = [1,2,3,3,3,4,4,5,5,5,5,5,5,8,9,9]
print_occur_times(my_array)