简体   繁体   English

我有对象数组,我的目标是仅使用 forEach 按升序打印对象的年龄

[英]I have array of objects, My goal is to print age of objects in ascending order using forEach only

I have Array in the name of students in that array I have four different objects.我以学生的名义在该数组中有 Array 我有四个不同的对象。 Now I have to print those objects, but the age should be in ascending order and I have to do this only by using forEach only.现在我必须打印这些对象,但年龄应该按升序排列,我只能通过仅使用forEach来执行此操作。

 var students = [{ name: 'Mark', age: 28 }, { name: 'Johnson', age: 30 }, { name: 'Williams', age: 12 }, { name: 'Henry', age: 27 } ] students.forEach(fun) function fun(currentValue, index, arr) { console.log(currentValue) }

You don't use forEach to sort an array, you use sort (unsurprisingly!)您不使用forEach对数组进行排序,而是使用sort (不足为奇!)

 var students = [{ name: 'Mark', age: 28 }, { name: 'Johnson', age: 30 }, { name: 'Williams', age: 12 }, { name: 'Henry', age: 27 } ] students.sort(sortByAge).forEach(fun) function sortByAge(a,b){ return a.age - b.age; } function fun(currentValue, index, arr) { console.log(currentValue) }

I think you have to sort the arrya and print it.我认为你必须对 arrya 进行分类并打印出来。

Hope this works.希望这有效。

 var students = [{ name: 'Mark', age: 28 }, { name: 'Johnson', age: 30 }, { name: 'Williams', age: 12 }, { name: 'Henry', age: 27 } ] function sortArray( a, b ) { if ( a.age < b.age ){ return -1; } if ( a.age > b.age ){ return 1; } return 0; } students.sort( sortArray ); students.forEach(fun) function fun(currentValue, index, arr) { console.log(currentValue) }

I hope this is a dynamic solution which is used your system in future as well.我希望这是一个动态的解决方案,将来也可以用于您的系统。

function dynamicSort(property) {
    var sortOrder = 1;
    if(property[0] === "-") {
        sortOrder = -1;
        property = property.substr(1);
    }
    return function (a,b) {
        /* next line works with strings and numbers, 
         * and you may want to customize it to your needs
         */
        var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
        return result * sortOrder;
    }
}

and it will work when you do:当你这样做时它会起作用:

students.sort(dynamicSort("name"));
students.sort(dynamicSort("name"));

If I'm understanding the problem correctly, you might be allowed to do a simple bubble sort.如果我正确理解了这个问题,你可能会被允许做一个简单的冒泡排序。

Assuming you had something like this假设你有这样的事情

var students = [{
    name: 'Mark',
    age: 28
  },
  {
    name: 'Johnson',
    age: 30
  },
  {
    name: 'Williams',
    age: 12
  },
  {
    name: 'Henry',
    age: 27
  }
]

console.log(bubbleSort(students.map(x => x.age)))

You might be able to use one of these two bubble sort algorithms您也许可以使用这两种冒泡排序算法之一

Using a foreach and a for loop使用 foreach 和 for 循环

let bubbleSort = (inputArr) => {
    let len = inputArr.length;
    inputArr.forEach(function(i){
        for (let j = 0; j < len; j++) {
            if (inputArr[j] > inputArr[j + 1]) {
                let tmp = inputArr[j];
                inputArr[j] = inputArr[j + 1];
                inputArr[j + 1] = tmp;
            }
        }
    })

    return inputArr;
};

Using a foreach and a do/while loop使用 foreach 和 do/while 循环

let bubbleSort = (inputArr) => {
    let len = inputArr.length;
    let swapped;
    do {
        swapped = false;
          inputArr.forEach(function(number, i){
            if (inputArr[i] > inputArr[i + 1]) {
                let tmp = inputArr[i];
                inputArr[i] = inputArr[i + 1];
                inputArr[i + 1] = tmp;
                swapped = true;
            }
          })
    } while (swapped);
    return inputArr;
};

https://www.studytonight.com/data-structures/bubble-sort https://www.studytonight.com/data-structures/bubble-sort

To sort any data it's requred minimum O(nlogn) operations, but forEach func will called only n times.要对任何数据进行排序,它需要最少的 O(nlogn) 操作,但 forEach 函数只会调用 n 次。 You hence unable to do it using forEach only.因此,您无法仅使用 forEach 来做到这一点。

But if you really want to use forEach only, let's use some magic with async js:但如果你真的只想使用 forEach,让我们对异步 js 使用一些魔法:

var students = [{
    name: 'Mark',
    age: 28
  },
  {
    name: 'Johnson',
    age: 30
  },
  {
    name: 'Williams',
    age: 12
  },
  {
    name: 'Henry',
    age: 27
  }
]

students.forEach(fun)

function fun(currentValue) {
  setTimeout(() => console.log(currentValue), currentValue.age);
}

Please, don't use this solution in production请不要在生产中使用此解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何按数字升序对对象数组进行排序? - How to sort an array of objects in ascending order of number? 在对象数组上使用forEach() - Using forEach() on an Array of Objects 我创建了一个只使用 JavaScript 的包含一些记录的表,我想将我的数组与对象设置为本地存储 - I have created a table with some records using with JavaScript only, I want to set my array with objects to local Storage 按升序对对象数组进行排序,但将所有零都放在末尾 - Sort an array of objects in ascending order but put all zeros at the end 按与另一个值相关的值的升序对对象数组进行排序 - Sorting array of objects by the ascending order of values related to another value 使用 forEach 将对象推入数组 - Pushing objects into array using forEach 按小时从最早到最新的升序对对象数组进行排序 - Sort an array of objects by hour minutes in ascending order from earliest to latest 在同一单击中按升序和降序对一组对象进行排序 - Sorting an array of objects on both ascending and descending order on same click 我正在操作一个对象数组,以便使用函数_.reject和_.uniqBy使用lodash获取唯一值 - I'm manipulating an array of objects in order to have unique values with lodash using the functions _.reject and _.uniqBy 我有一个数组,我想使用下划线js按升序排序 - I have an array i want to sort it in ascending order using underscore js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM