I have the following JavaScript array of objects:
[{name: '4 Arn', isLetter: false},
{name: 'Abax', isLetter: false},
{name: 'Aramex', isLetter: false},
{name: 'Booking', isLetter: false},
{name: 'Dangerous', isLetter: false},
{name: 'Manali', isLetter: false}]
In the above array, I want to check the first letter of each item's name
property. If it matches, I want to append a new object just before the object, as shown in the following examples:
[{letter: "#", isLetter: true}, // new object
{name: '4 Arn', isLetter: false},
{letter: "A", isLetter: true}, // new Object
{name: 'Abax', isLetter: false},
{name: 'Aramex', isLetter: false},
{letter: "B", isLetter: true}, // new object
{name: 'Booking', isLetter: false},
{letter: "D", isLetter: true}, // new object
{name: 'Dangerous', isLetter: false},
{letter: "M", isLetter: true}, // new object
{name: 'Manali', isLetter: false}]
I tried the reduce()
function, but I don't understand why it's giving me the wrong result:
var newArr = [];
list.reduce(function(prev, cur, index, originalArrray) {
var previousCharcode = prev.name.toUpperCase().charCodeAt(0);
currentCharCode = cur.name.toUpperCase().charCodeAt(0);
newArr.push(prev);
if(previousCharcode != currentCharCode) {
newArr.splice(index, 0, {isLetter: true, letter: String.fromCharCode(currentCharCode)});
}
return cur;
});