Home > Web Front-end > JS Tutorial > code war daily practice

code war daily practice

巴扎黑
Release: 2017-06-27 09:12:31
Original
1580 people have browsed it

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;
    }
  })
}
Copy after login

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;
}
Copy after login

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 }));
}
Copy after login

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);
}
Copy after login

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)
}
Copy after login

The above is the detailed content of code war daily practice. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template