JavaScript: Better way to sort an array by setting custom index I'm trying to create a sorted array based on the below input data:
Input:
[{&quot;title&quot;: &quot;100_baz&quot;}, {&quot;title&quot;: &quot;01_foo&quot;}, {&quot;title&quot;: &quot;05_bar&quot;}]
function indexSort (input) {    
    let output = [];
    input.forEach(value =&gt; {    
        if (value.title &amp;&amp; value.title.indexOf('_') !== -1) {
            let targetIndex = parseInt (value.title.split('_')[0]);
            let title = value.title.substring(value.title.indexOf('_') + 1, value.title.length); // extract the string next to '_'
            output[targetIndex] = title;
        }    
    })
    console.log(output)
}

Desired Output:

I'm able to get the desired output using the above code snippet, however, I'm looking for a better way to achieve this in terms of good practice, or a concise and clear method in ES5 or ES6.
Updating my comments on current implementation, Thanks @Mast for pointing out.


You have used let for output, targetIndex and title. None of
them never updated. const is better suitable here. 
Usage of value.title.indexOf('_') is repeated. you can use variable.
You can avoid substring usage because you are already did value.title.split('_') and you can use index 1 value from result
    array.


Apart from these minor points, code looks good to me.

As you asked, Here is alternative ES6 implementation.


Use arrow function
With reduce and using destructure in input function arguments and have the default value for title.
In reduce function use destucture to get the values from split result.




const data = [{"title": "100_baz"}, {"title": "01_foo"}, {"title": "05_bar"}];

const indexSort = data =&gt; data.reduce((acc, {title = ''}) =&gt; {
  const [num, value] = title.split('_');
  acc[Number(num)] = value;
  return acc;
}, []);

console.log(indexSort(data));