JavaScript algorithm problem (i) && array reduce use

Source: Internet
Author: User

Refer to Array.reduce Usage

1. Write the Getmissingelement function to return the missing element in the given array (the element in the array is 0~9, only one is missing).

Example:

Getmissingelement ([0, 5, 1, 3, 2, 9, 7, 6, 4]) //returns 8

Getmissingelement ([9, 2, 4, 5, 7, 0, 8, 6, 1]) //returns 3

Soluction:

function Getmissingelement (superimportantarray) {  return superimportantarray.reduce (function (sum,i) {return SUM-I;},45)}

2.Write a function that flattens an array of the array objects into a flat array. Your function must only does one level of flattening.

Exmaple:

Flatten ([123])//= [+/-]

Flatten ([[1,2,3],["A", "B", "C"],[1,2,3]])//=>[1,2,3, "A", "B", "C", [+])

Flatten ([[[[[I]]])//= [[[+]]

Soluction:

var flatten = function (array) {   return array.reduce (function (b) {       return a.concat (b);   },[])}

  




JavaScript algorithm problem (i) && array reduce use

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.