The first question
The id
// Requirements: two arrays, final output:
// [' Employee Zhang SAN, 29, works in Baidu ', 'Employee Li Si, 26, works in Alibaba ',...]
var employees = [
{
name: "Zhang".// Employee name
empId: 0./ / employee id
age: 29.// Age of employee
compId: 1.// Id of the owning company
},
{
name: "Bill".empId: 1.age: 26.compId: 2}, {name: "Fifty".empId: 2.age: 28.compId: 1}, {name: "Xiao Ming".empId: 3.age: 32.compId: 3,},];var companies = [
{
name: "Baidu".// Company name
id: 1./ / company id
},
{
name: "Alibaba".id: 2}, {name: "Tencent".id: 3,},];/* Target data structure [' Employee Zhang SAN, 29, works for Baidu ', 'Employee Li Si, 26, works for Alibaba ',...] * /
Copy the code
The first method:
// 1. Run the compId field from employees to companies for name
// Parameter: id Returns name
function getCompName(id) {
/* let name = null; companies.forEach(item=>{ if(item.id == id){ name = item.name; } }) return name; * /
for (let i = 0; i < companies.length; i++) {
if (companies[i].id == id) {
returncompanies[i].name; }}}// console.log(getCompName(2));
// 2. Iterate through the list of employees, putting a specific string into a new array
function getNewArr(arr) {
let newArr = [];
arr.forEach(item= > {
// console.log(' employee ${item.name}, ${item.age} age, work at ${getCompName(item.pid)} ');
newArr.push(` employees${item.name}.${item.age}Years old, working at${getCompName(item.compId)}`);
})
return newArr;
}
console.log(getNewArr(employees));
Copy the code
The second method:
var arr = []
employees.forEach(e= > {
companies.forEach(el= > {
if (e.compId == el.id) {
arr[arr.length] = ('employees' + e.name + ', ' + e.age + 'Aged, working at' + el.name)
/ / arr. Push (the 'employees' + e.n ame +', '+ e.a ge +' age, working in + el. Name)
. / / the console log (' employees' + e.n ame + ', '+ e.a ge +' age, working in + el. Name);}})})console.log(arr);
Copy the code
The second question
Object to array
/ / requirement: please make the following array is: [[' apple ', 'carrots',' peanuts'], [' pear ', 'celery', 'nuts']...].
var basket = [
{ fruit: The word "apple".veg: "Carrot".nut: "Peanuts" },
{ fruit: "Pear".veg: "Celery".nut: "Nuts" },
{ fruit: "Banana".veg: "Potato".nut: "Apricot kernel" },
{ fruit: "Watermelon".veg: "Bean sprouts".nut: "Nuts"}];Copy the code
The first:
// 1
/* var newArr = []; basket.forEach((item,index)=>{ // console.log(item); / / 2. The initialization of a two-dimensional array / / expected data structure [[], [], [], []] newArr. Push ([]); For (let key in item){newArr[index]. Push (item[key])}}) console.log(newArr); * /
Copy the code
The second:
/* var newArr = []; basket.forEach(item=>{ // console.log(Object.values(item)); Newarr.push (object.values (item))}) console.log(newArr); * /
Copy the code
The third kind of
Var arr = [1, 2, 3, 4, 5]; var arr = [1, 2, 3, 5]; var newArr = arr.map((item,index)=>{ // console.log(item,index); Return item+" You are so strong!!" }) console.log(newArr); * /
var newArr = basket.map(item= >{
return Object.values(item);
})
console.log(newArr);
Copy the code
A fourth
var arr = []
var list = []
basket.forEach(e= > {
for (key in e) {
list[list.length] = e[key]
}
arr[arr.length] = list
list = []
})
console.log(arr);
Copy the code
The third question
Data statistics
/* Requirement: the program implements the statistics of the number of occurrences of the data and sorts them according to the number of occurrences. [1 to 4] is passed into the JS method as a parameter (** variable parameter **). The console outputs the following result: 1 appears 3 times, 2 appears 2 times, 4 appears 2 times, 3 appears 1 time */Copy the code
// 1. The parameters in the array are mutable
function getRandomArr(min, max, total) {
let arr = [];
for (let i = 0; i < total; i++) {
arr.push(Math.floor(Math.random() * (max - min + 1) + min))
}
return arr;
}
let randomArr = getRandomArr(1.5.10);
console.log(randomArr);
// 2. Function encapsulation
// Argument :randomArr does not need to return a value
function countNum(arr) {
// 3. Initialize the object
// Idea: initialize a value of 1 and add
// Expected data type:
/* {1:2, 2:2; 4:1... } * /
let obj = {};
// 4
arr.forEach(item= > {
// Object adds/modifies attribute values,
// obj.name = XXX if this key is not added, if it is modified
// 5. Determine when to initialize a key number 1
if (obj[item]) {
obj[item]++;
} else {
obj[item] = 1; }})// console.log(obj);
// 6. Object traversal, print the required text
/ / 7. Sorting
let newArr= [];
for(let k in obj){
// console.log(' ${k} appears ${obj[k]} times');
newArr.push({num:k,count:obj[k]})
}
// console.log(newArr);
newArr.sort((a,b) = >{
return a.count-b.count;
}).forEach(item= >{
// console.log(item);
console.log(`${item.num}the${item.count}Time `);
})
}
countNum(randomArr);
Copy the code
The fourth question
Array row to column
// Need to implement 2 d array row transform column
var arr = [
["Front end"."Three people"."8-15k"."Undergraduate"],
["Back-end"."5"."10-25k"."Graduate student"],
["UI"."Two people"."9-11k"."College"],
["ETL Engineer"."10 people"."6-12k"."College"]];/ * conversion = > var newArr = [[" front ", "back-end", "UI", "the ETL engineer"], [" three people ", "5", "2", "10"], [8-15 "k", "10 to 25 k", "September 11 k", "6 and 12 k"]. [" undergraduate ", "graduate "," junior college ",]; * /
Copy the code
Methods a
// select * from row 1 to row 2
let newArr = [];
// 1. Arr [0]
for (let i = 0; i < arr[0].length; i++) {
// Expected data type:
/ / /
/ / []
/ / []
/ / []
/ / []
/ /]
// 2. Column initialization
newArr[i] = [];
// 3
for (let j = 0; j < arr.length; j++) {
// Expected data type:
/ / /
// [" front end ", "back end ", "UI", "ETL engineer "]
/ / []
/ / []
/ / []
/ /]
// 4. Column data into rowsnewArr[i][j]= arr[j][i]; }}console.log(newArr);
Copy the code
Method 2
// 1 row to row 2 column to row
let newArr = arr[0].map((col, index) = > {
// Return similar to newArr[I] = [];
return arr.map(row= >{
// return is like [" front end ", "back end ", "UI", "ETL engineer "]
returnrow[index]; })})console.log(newArr);
Copy the code
Methods three
var arr2 = []
var arr3 = []
function list(num) {
arr.forEach(function (e) {
arr2[arr2.length] = e[num]
})
arr3[arr3.length] = arr2
arr2 = []
}
for (var i = 0; i < arr.length; i++) {
list(i)
}
console.log(arr3);
Copy the code
The fifth problem
Object array to reorder
// Select * from (name, sales);
var arr = [
{ name: "Xiao Ming".year: 2019.sales: 53 },
{ name: "Xiao Ming".year: 2020.sales: 234 },
{ name: "Xiao Ming".year: 2018.sales: 24 },
{ name: "Small strong".year: 2019.sales: 31 },
{ name: "Small strong".year: 2020.sales: 567 },
{ name: "Small strong".year: 2018.sales: 678 },
{ name: "Little red".year: 2019.sales: 465 },
{ name: "Little red".year: 2020.sales: 82 },
{ name: "Little red".year: 2018.sales: 576 },
{ name: "Pony".year: 2019.sales: 4567 },
{ name: "Pony".year: 2020.sales: 832 },
{ name: "Pony".year: 2018.sales: 674},];Copy the code
Var arr = [1,2,1,7,4,6,4,6,4,7]; Console. log(arr.sort((a,b)=>{// ascending // return a-b; // return b-a; })); * /
// 1. The function wraps a new array of arr returns values
function getArrayObject(arr){
let obj = {};
// 2. Sort the sales attribute (ascending)
arr.sort((a,b) = >{
// a b corresponds to the array value {}
return a.sales-b.sales;
// 3. Deduplicate the maximum sales data for name
}).forEach(item= >{
// console.log(item);
// Assign a value to the key, and if it exists, modify it (overwrite it)
/ * the expected data type: {" Ming ": {name:" xiao Ming, "year: 2020, the sales: 234}," ma ": {name:" pony, "year: 2019, the sales: 4567},} * /
obj[item.name] = item;
})
// console.log(arr);
// console.log(obj);
// 4. Return a new array
return Object.values(obj);
// return new array
}
console.log(getArrayObject(arr));
Copy the code
Method 2
// Set the required variables
var list = [], arr2 = [], num = 0
// Save the first data first
list[0] = arr[0]
// console.log(list);
for (var i = 1; i < arr.length; i++) {
// If name is equal, put it in the list array
if (list[list.length - 1].name == arr[i].name) {
list[list.length] = arr[i]
/ / sorting
list.sort(function (min, max) {
return min.sales - max.sales
})
// assign arr2 num
arr2[num] = list[list.length - 1]}else {
// if name, then use arr[I] to overwrite the data before the list, and num++
list = [arr[i]]
num++
}
}
// Sort the values by sales
arr2.sort(function (min, max) {
return min.sales - max.sales
})
console.log(arr2);
Copy the code