Javascript: Keep Track of Parent in Array Example

by Matthew Marcus

HTML

<button onclick="doIt();">Do It!</button>

JavaScript

var arr = [{
    title: 'object0',
    value: 0
}, {
    title: 'object1',
    value: 1
}, {
    title: 'object2',
    value: 2
}, {
    title: 'object3',
    value: 3
}, {
    title: 'object4',
    value: 4
}];

var newRow = {
    title: 'newRow',
    parent: arr[2]
};

arr.splice(3, 0, newRow);
console.log(JSON.stringify(arr));

arr.splice(3, 1);
console.log(JSON.stringify(arr));

window.doIt = function() {

    arr = d3.shuffle(arr);
    console.log(JSON.stringify(arr));

    document.getElementsByTagName("body")[0].innerHTML += 'newRow parent Index: ' + arr.indexOf(newRow.parent) + '<br />';
}