title: Find First and Last Position of Element in Sorted Array
body: <p>I am trying to solve the LeetCode problem <a href="https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array" rel="nofollow noreferrer">Find First and Last Position of Element in Sorted Array</a>:</p>
  <blockquote>
  <p>Given an array of integers <code>nums</code> sorted in ascending order, find the starting and ending position of a given <code>target</code> value.</p>
  <p>If <code>target</code> is not found in the array, return <code>[-1, -1]</code>.</p>
  <p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p>
  </blockquote>
  <p>I am writing this code:</p>
  <pre><code>var searchRange = function(nums, target) {
    nums = nums.sort((a, b) =&gt; (a-b))
    let result = [];
    for(let i = 0; i &lt; nums.length; i++) {
      if (nums[i] == target) {
        result.push(i)
      } else {
       result = [-1, -1]
      }
    }
  
    return result
  };
   
  console.log(searchRange([5,7,7,8,8,10], 8));
  </code></pre>
  <p>It should return:</p>
  <pre><code>[3, 4]
  </code></pre>
  <p>but it returns:</p>
  <pre><code>[-1, -1]
  </code></pre>
  <p>What is wrong?</p>