jquery's map doesn't return native array, you need to use get()

slideHeights = $('*[data-anchor]').map(function(i, item) {
    return Math.floor($(item).offset().top);
}).get(); 

Or use toArray

slideHeights = $('*[data-anchor]').map(function(i, item) {
    return Math.floor($(item).offset().top);
}).toArray(); 
Answer from gurvinder372 on Stack Overflow
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Unshift not a function? - JavaScript - The freeCodeCamp Forum
March 29, 2021 - Tell us what’s happening: Describe your issue in detail here. Your code so far .unshift not a function and same with push??? function reverseString(str) { let reverse = [str]; let reversed = ""; for (let i = 0; i < …
🌐
Scaler
scaler.com › home › topics › javascript array unshift() method
JavaScript Array unshift() Method - Scaler Topics
February 23, 2024 - **Type Error:** unshift is not a function - error in javascript. It occurs when the value called is not an array.
🌐
Servoy
forum.servoy.com › viewtopic.php
Servoy Forum • View topic - array.unshift() not working on NativeArray object
var arrayStatus = Array(application.getValueListArray('status_off_acq')); var arrayStatus2 = arrayStatus; arrayStatus.unshift('Tutti'); arrayStatus2.unshift('%'); application.setValueListItems('off_acq_righe_filtro_status',arrayStatus,arrayStatus2); Nope. The result is a list like this: ... Well I did some quick testing (instead of guessing ). It seems that this VERY new function is not that polished. ... var arrayStatus = application.getValueListArray('testvaluelist'); This results in a org.mozilla.javascript.NativeArray as shows in the debugger.
🌐
Reactgo
reactgo.com › home › how to solve unshift is not a function error in javascript
How to solve unshift is not a function error in JavaScript | Reactgo
January 4, 2023 - The “unshift is not a function” error occurs, when we call a unshift() method on a value which is not an array. To solve the error convert the value to an array before calling the unshift() method on it or make sure to use unshift() method ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › unshift
Array.prototype.unshift() - JavaScript | MDN
The unshift() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.
Top answer
1 of 1
2

Array#unshift is an in-place function that mutates the array it's called upon. unshift returns the length of the updated array. The reason it fails after adding an item is because you've replaced what should be an array with a number. Number.map is not a thing so the program crashes.

The golden rule of React is "never mutate state" because it confuses React's diffing algorithm as it attempts to figure out what to rerender, with unpredictable results. Make a copy if you need to use a mutating function like unshift.

Try Array#concat instead of unshift here. concat is non-mutating and returns a copy of the array it's called on, so there will be no problems with React and it's safe to use inline directly in the object you're passing to setState.

A second problem is reading state values inside of the setState call, like this.state.todos.length. Use the callback version of setState that accepts the previous state as a parameter:

this.setState(prevState => ({
  todos: [{
    id: prevState.todos.length + 1,
    title: prevState.value,
    completed: true
  }].concat(prevState.todos)
}));

Spread syntax works in place of concat here. The code below also fixes a bug where this.props.map was used instead of this.state.map and doesn't use an <input> as a child element of a <ul>.

class TodoList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      todos: this.props.todos,
      value: ""
    };
    this.handleChange = this.handleChange.bind(this);
  }

  addTodo(e) {
    e.preventDefault();
    this.setState(prevState => ({
      todos: [{
        id: prevState.todos.length + 1,
        title: prevState.value,
        completed: true
      }, ...prevState.todos]
    }));
  }

  handleChange(e) {
    this.setState({value: e.target.value});
  }

  render() {    
    return (
      <div>
        <h1>Todos:</h1>
        <form onSubmit={(e) => this.addTodo(e)}>
          <input type='text' 
                 value={this.state.value} 
                 onChange={this.handleChange} />
        </form>
        <ul className='todo-list'>
          { 
            this.state.todos.map(todo =>              
              <React.Fragment key={todo.id}>
                <li className={
                  `todo-item ${todo.completed 
                   ? 'todo-item-completed' 
                   : ''}`
                }>
                  { todo.title }
                  <input
                    readOnly
                    type='checkbox'
                    checked={todo.completed}
                  />
                </li>
              </React.Fragment>
            ) 
          }
        </ul>
      </div>
    )
  }
}

ReactDOM.createRoot(document.querySelector("#app"))
  .render(<TodoList todos={[]} />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="app"></div>

Using function components and the state hook moves pieces of state into distinct variables, simplifying state management in most use cases.

As a side note, prevState.todos.length + 1 may be a poor way to generate ids if you introduce the option to delete todos. I could add a todo and make the length 1, add a second todo to make the length 2. Then, if I delete the first item with id 1 and create a new item, I have two items with id set to 2. A monotonically increasing number or UUID might be better.

🌐
Vertstudios
vertstudios.com › blog › jquery-unshift-not-a-function-solution
jQuery unshift is not a function : Solution! | Vert Studios
At times, jQuery can induce some scope issues when it comes to using the JavaScript array prototypes. One example in particular is the unshift() array prototype. In the same context as array.push(), Firebug may throw the error that unshift is not a function.
Find elsewhere
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Please help, TypeError: remove.shift() is not a function
November 23, 2017 - Tell us what’s happening: Your code so far function nextInLine(arr, item) { // Your code here var remove = arr.push(item); return remove.shift(); // Change this line } // Test Setup var testArr = [1,2,3,4,5]; // Display Code console.log("Before: " + JSON.stringify(testArr)); console.log(nextInLine(testArr, 6)); // Modify this line to test console.log("After: " + JSON.stringify(testArr)); **Link to the challenge:** https://www.freecodecamp.org/challenges/stand-in-line
🌐
W3Schools
w3schools.com › jsref › jsref_unshift.asp
JavaScript Array unshift() Method
The unshift() method overwrites the original array. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make ...
🌐
Meticulous
meticulous.ai › blog › javascript-unshift-complete-guide
JavaScript Unshift | In-Depth Guide & Tutorial
You will notice here that arr is mutated. We assigned the returned value to a new variable res, which contains the length of the new array. The original array arr was mutated and contains a different value before and after the .unshift call. Mutation is something to be careful about because it is a common cause of unexpected issues which can be tricky to debug. To drive this point home, the paradigm of functional programming has an explicit goal of avoiding mutation and having pure functions (functions without mutation or side effects) for this very reason.
🌐
PRAJWAL'S BLOG
prajwalbhatia.hashnode.dev › polyfill-javascript-array-unshift-method
Javascript unshift method
December 8, 2022 - //Whenever we will call [].customUnshift(1) //this -> [] function customUnshift() { //First we will check the type of this if(this === null || this === undefined) { throw new TypeError('.unshift is not a function') } } Array.prototype.customUnshift = customUnshift;
🌐
KUTAI99
itsjavascript.com › typeerror-unshift-is-not-a-function
[Solved] TypeError: unshift is not a function - ItsJavaScript
kutai99 bandar togel terpercaya yang memiliki biaya bet yang terjangkau 100 rupiah dan kutai99 memberikan pengalaman bermain judi online terlengkap dengan beragam permainan.
🌐
SheCodes
shecodes.io › athena › 18575-difference-between-array-shift-and-array-unshift-in-javascript
[JavaScript] - Difference between array.shift() and | SheCodes
Learn how to use array.shift() and array.unshift() methods in JavaScript to manipulate elements in an array ... How do I make a javascript event where you click on a thumbnail image and it pops up with a full sized image? JavaScript event handling image pop-up thumbnail DOM manipulation ... Is my JS code correct?
🌐
GitHub
github.com › emberjs › ember.js › issues › 11500
array.unshift() throwing error on init: "Uncaught TypeError: Cannot read property 'key' of null" · Issue #11500 · emberjs/ember.js
March 20, 2015 - Hello, I am simply formatting an array to be rendered with the {{#each}} helper, and I am getting this error only when I add an element to the array using unshift. ... setTimes: function() { var times = []; for (var i =0;i<2;i++) { for (var i2=1;i2<13;i2++) { var timeOfDay = i==0 ?
Published   Jun 18, 2015
🌐
AppDividend
appdividend.com › 2022 › 07 › 04 › javascript-unshift
JavaScript Array unshift() Method
November 23, 2023 - JavaScript Array unshift() method is used to add one or more elements to the beginning of an array.