1.改成如下那种样子的
var animals = [ { name: 'lili', species: 'dog' }, { name: 'mimi', species: 'cat' }, { name: 'jone', species: 'dog' }, { name: 'kity', species: 'rabbit' }, { name: 'tom', species: 'fish' }, { name: 'jetty', species: 'cat' } ] //获取所有的狗 /*获取下面的数据 { dog: ['lili', 'jone'], cat: ['mimi', 'jetty'], rabbit: ['kity'], fish: ['tom'] } */
写一个函数
function getDogs(animalsList) { let animalsObj = {}; animalsList.forEach(item => { if (!animalsObj[item.species]) { animalsObj[item.species] = []; } animalsObj[item.species].push(item.name); }); return animalsObj; }
2.
arr = [1, 2, [3, [4, [5, [6, 7, 8, [9]]]]]]改成[1,2,3,4,5,6,7,8,9]
const isArr = Array.isArray; function f(arr) { if (!isArr(arr)) { return arr; } let newA = []; arr.forEach(item => { if (isArr(item)) { newA = newA.concat(f(item)); } else { newA.push(item); } }); return newA; } let arr = [1, 2, [3, [4, [5, [6, 7, 8, [9]]]]]]; console.log(f(arr));