How to sort strings in JavaScript

后端 未结 12 2186
生来不讨喜
生来不讨喜 2020-11-22 13:20

I have a list of objects I wish to sort based on a field attr of type string. I tried using -

list.sort(function (a, b) {
    retur         


        
12条回答
  •  一个人的身影
    2020-11-22 13:29

    An explanation of why the approach in the question doesn't work:

    let products = [
        { name: "laptop", price: 800 },
        { name: "phone", price:200},
        { name: "tv", price: 1200}
    ];
    products.sort( (a, b) => {
        {let value= a.name - b.name; console.log(value); return value}
    });
    
    > 2 NaN
    

    Subtraction between strings returns NaN.

    Echoing @Alejadro's answer, the right approach is--

    products.sort( (a,b) => a.name > b.name ? 1 : -1 )

提交回复
热议问题