最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I use .map method to sort items in array if possible - Stack Overflow

programmeradmin1浏览0评论

The question of the challenge is :

Modify the function to return a copy of the given array sorted in ascending order (1, 2, 3, etc). Do not modify the original array.

I've tried doing a normal for loop and an if statement :

let original = [1, 7, 3, 5];
let sortedCopy = []
for (i = 0; i < original.length; i++){
    if (original[i] > original[i+1]){
        sortedCopy.push.([1])
    } 
}
console.log(sortedCopy);

Now I'm trying to use a .map method since it automatically loops and passes each number through the callback

function copyAndSortNumbers(numbers) {
  this.numArray = numbers;
  numArray.map(sortingArray)
  function sortingArray (numbers){
    if (numbers[i] > numbers[i+1]){
      return numbers;
    }
  }
}

const original = [1, 7, 3, 5];
const sortedCopy = copyAndSortNumbers(original);

I should get a new ordered array but I don't see what I'm missing

Edit:

here is an updated version, it's now returning an array but still not sorting it

function copyAndSortNumbers(numbers) {
  numArray = numbers;
  numArray.map(sortingArray)
  function sortingArray (numbers){
    if (numbers > numbers + 1){
      return numbers;
    }
  }
  return numArray;
}

The question of the challenge is :

Modify the function to return a copy of the given array sorted in ascending order (1, 2, 3, etc). Do not modify the original array.

I've tried doing a normal for loop and an if statement :

let original = [1, 7, 3, 5];
let sortedCopy = []
for (i = 0; i < original.length; i++){
    if (original[i] > original[i+1]){
        sortedCopy.push.([1])
    } 
}
console.log(sortedCopy);

Now I'm trying to use a .map method since it automatically loops and passes each number through the callback

function copyAndSortNumbers(numbers) {
  this.numArray = numbers;
  numArray.map(sortingArray)
  function sortingArray (numbers){
    if (numbers[i] > numbers[i+1]){
      return numbers;
    }
  }
}

const original = [1, 7, 3, 5];
const sortedCopy = copyAndSortNumbers(original);

I should get a new ordered array but I don't see what I'm missing

Edit:

here is an updated version, it's now returning an array but still not sorting it

function copyAndSortNumbers(numbers) {
  numArray = numbers;
  numArray.map(sortingArray)
  function sortingArray (numbers){
    if (numbers > numbers + 1){
      return numbers;
    }
  }
  return numArray;
}
Share Improve this question edited Feb 7, 2019 at 12:47 rodpadev asked Feb 7, 2019 at 12:04 rodpadevrodpadev 3931 gold badge4 silver badges20 bronze badges 3
  • 4 1. That's not what .map() should be used for 2. Have a look at: Array.prototype.map() on how .map() works and what the arguments of the callback are – Andreas Commented Feb 7, 2019 at 12:06
  • .map() !== .sort() – Osakr Commented Feb 7, 2019 at 12:09
  • "How can I use .map() to sort items" - you don't. I'm really puzzled by the amount of people who seem to use .map() things it's not supposed to. And by this I mean as a replacement to .forEach(). I'm not sure where that misconception is ing from. – VLAZ Commented Feb 7, 2019 at 13:01
Add a ment  | 

4 Answers 4

Reset to default 7

You can use slice to copy the array and then sort to sort the new array.

const original = [1, 7, 3, 5];
const sorted = original.slice().sort((a, b) => a - b)

console.log(original, sorted)

Comparison of array copy method speed.

For getting a sorted array, you need two nested loops, one for the given array and one for finding the position for inserting the actual element.

var array = [1, 7, 3, 5],
    copy = array.slice(0, 1),
    i, j;
  
outer: for (i = 1; i < array.length; i++) {
    for (j = 0; j < copy.length; j++) {
        if (array[i] < copy[j]) {
            copy.splice(j, 0, array[i]);
            continue outer;
        }
    }
    copy.push(array[i]);
}

console.log(copy);

Using the spread syntax may be simpler and returns a new array.

const initial = [1, 7, 3, 5];
const sorted = [...initial].sort((a, b) => a - b)

console.log(initial, sorted)

Lots. First of all,

numArray.map(sortingArray)

should throw an error because numArray is not defined. You have this.numArray, which is not the same thing. If that weren't an issue, the line does nothing, since you don't assign the result to anything. But even that doesn't work, because i is undefined in your callback... and the callback does no sorting, whatsoever.

To create a copy of an array, you can use let copy = numbers.slice(), let copy = Array.from(numbers), let copy = [...numbers], or indeed let copy = numbers.map(x => x); this last one is the slowest EDIT: Apparently, Array.from is currently slowest, and destructuring is slow on Firefox, which actually executes map as fast as slice. Go figure. A good reminder even to veterans never to assume performance without testing.

To sort that copy then, copy.sort((a, b) => a - b) suffices.

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>