From db75c259febd89b18df6aca4e34c0d57b83517ba Mon Sep 17 00:00:00 2001 From: Imran Khan <99397606+imran120198@users.noreply.github.com> Date: 2023年4月28日 21:42:08 +0530 Subject: [PATCH] added code snippet 34 --- README.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/README.md b/README.md index 3780dcc..f74ac4f 100644 --- a/README.md +++ b/README.md @@ -1018,3 +1018,33 @@ Since a and b reference the same array, both console.log(a) and console.log(b) w This is different from the previous example where ... spread operator was used, which created a new array with the same values as the original array instead of referencing the same array. + +
+ +

34. What is the output of the following code?

+ +```jsx +var companies = [ + {id: "1", name:"Facebook"}, + {id: "2", name:"Apple"}, + {id: "3", name:"Google"}, +] + +companies.sort((a,b) => (a.name> b.name ? -1 : 1)) +console.log(companies) + +``` + +
+ +The output of the code will be: + +Answer: + +```bash +[ {id: "3", name:"Google"} , {id: "1", name:"Facebook"} , {id: "2", name:"Apple"} ] +``` + +The comparison function takes two parameters, "a" and "b", which represent two elements being compared in the array. If the "name" property of "a" comes before the "name" property of "b" in alphabetical order, then the function returns -1, which means "a" should come before "b" in the sorted array. Otherwise, if the "name" property of "a" comes after the "name" property of "b" in alphabetical order, then the function returns 1, which means "b" should come before "a" in the sorted array. + +

AltStyle によって変換されたページ (->オリジナル) /