Home >Web Front-end >JS Tutorial >code war daily practice
Do a question in your spare time:
This question means: delete the same adjacent elements and return a new array.
It’s best to use the Array.filter method here. My answer is as follows:
var uniqueInOrder=function(iterable){ var arr = typeof(iterable) === 'string' ? iterable.split('') : iterable; var pre = ''; return arr.filter(function(i){if(i === pre){ return false; }else{ pre = i; return true; } }) }
Note here that filter will not modify the original array. It only returns a new array, and also has a function: delete the values that return false, and keep the values that return true.
There is a second answer:
var uniqueInOrder=function(iterable){ var arr = typeof(iterable) === 'string' ? iterable.split('') : iterable; var pre = '',result = []; arr.map(function(i){if(i !== pre){ result.push(pre = i); } }); return result; }
This is to use another empty array to reproduce the qualified values.
After submitting, I saw a very smart answer in the Solutions area:
var uniqueInOrder = function (iterable){ return [].filter.call(iterable, (function (a, i) { return iterable[i - 1] !== a })); }
The call method is used here to make iterable cleverly call array.filter. I don’t know what this means. The same applies to whether it is an array or a string iterable. There is no need to go through the trouble of converting the string into an array for operation.
Then he took advantage of the characteristics of the filter return value and compared each element with the previous element in turn. If they are not equal, it returns true and retains the current element.
This question is relatively simple.
Another simple question:
This is very simple, so I will post the answer directly:
function average(scores) { var result = 0; scores.map(i=>result+=i); return Math.round(result/scores.length); }
The best way to show the conclusion area by example:
function average(scores) { return Math.round(scores.reduce((x, y) => x+y, 0) / scores.length) }
The above is the detailed content of code war daily practice. For more information, please follow other related articles on the PHP Chinese website!