Java Why use spread operator when sorting an array in JavaScript?

  • Thread starter Thread starter shivajikobardan
  • Start date Start date
  • Tags Tags
    Javascript Operator
AI Thread Summary
The discussion centers on the use of the spread operator in JavaScript, particularly in the context of creating a new array from an existing one. The spread operator, represented as `[...]`, is demonstrated with an example where it copies an array of girl names. The user expresses confusion about its necessity in the `createList` function, which processes an array of `richestPeople`. It is clarified that the spread operator creates a shallow copy of the array, allowing for operations like sorting without altering the original array. Without the spread operator, using `[arr]` results in a nested array instead of a flat copy, which leads to incorrect output when generating list items. However, it is also noted that the function can work without the spread operator if the intention is to sort the original array directly. The discussion highlights that while the spread operator is useful for creating copies, alternatives like `slice()` can achieve similar results, and both methods can lead to the same output in certain scenarios.
shivajikobardan
Messages
637
Reaction score
54
TL;DR Summary
spread operator javascript
I Understand the basic theory behind spread operator.

JavaScript:
const girlNames = ['Jessica', 'Emma', 'Amandine']
const newGirlNames = [...girlNames]
console.log(newGirlNames)
// Output: ["Jessica", "Emma", "Amandine"]

But I don't understand when it's applied. See here.

JavaScript:
function createList() {
  [...richestPeople]
    .map(a => ({ value: a, sort: Math.random() }))
    .sort((a, b) => a.sort - b.sort)
    .map(a => a.value)
    .forEach((person, index) => {
      const listItem = document.createElement("li");
      listItem.setAttribute("data-index", index);
      listItem.innerHTML =
        `
    <span class="number">${index + 1}</span>
    <div class="draggable" draggable="true">
    <p class="person-name">${person}</p>
    <i class="fa-solid fa-grip-lines"></i>
    </div>

    `

      listItems.push(listItem);
      draggable_list.appendChild(listItem);
    })
}

Why do we require spread operator here? I tried to see the output w/o spread operator and seeing that didn't help.
output with spread operator:
1673710726254.png


output without spread operator:
1673710757527.png


It must be obvious to people, but it's not to me. I'm not getting it.
 
Technology news on Phys.org
This suggests that [...arr] is an efficient way of creating a copy of the one-dimensional array arr. Without the operator, you have [arr], an array consisting of a single entry, namely arr. Hence your second screenshot has the entire list of names as a comma-separated string in a single <li> tag, rather than each name in its own <li> tag as in the first screenshot.
 
Last edited:
shivajikobardan said:
JavaScript:
function createList() {
  [...richestPeople]
    .map(a => ({ value: a, sort: Math.random() }))
    // ...
}
Why do we require spread operator here? I tried to see the output w/o spread operator and seeing that didn't help.
You don't. The code below has exactly the same result.
JavaScript:
function createList() {
  richestPeople
    .map(a => ({ value: a, sort: Math.random() }))
    // ...
}
But note
JavaScript:
function createList() {
// This sorts the array richestPeople.
richestPeople.sort();
// This creates a new array of the elements of richestPeople and sorts it.
// richestPeople is left unsorted.
sortedRichestPeople = [...richestPeople].sort();
// This code has an identical result and is preferred by some:
sortedRichestPeople = richestPeople.slice().sort();
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I had a Microsoft Technical interview this past Friday, the question I was asked was this : How do you find the middle value for a dataset that is too big to fit in RAM? I was not able to figure this out during the interview, but I have been look in this all weekend and I read something online that said it can be done at O(N) using something called the counting sort histogram algorithm ( I did not learn that in my advanced data structures and algorithms class). I have watched some youtube...

Similar threads

Back
Top