gdh48k
gdh48k

Reputation: 29

Updating elements of a multidimensional array

I'm seeking to update a team results array below. The football score will populate positions 1 and 2 of each inner array.

var teamResults=[
  ["Home","F","A","Away"],
  ["A",,,"B"],
  ["A",,,"C"],
  ["B",,,"C"],
  ["B",,,"A"],
  ["C",,,"A"],
  ["C",,,"B"],
];

Initially each score is undefined as below:

console.log(teamResults[1]);

 ["A" ,undefined ,undefined ,"B"]

Using 'splice' works to update team A's score in fixture #1:

teamResults[1].splice(1,1,3);

["A" ,3 ,undefined ,"B"]

However, using the same method for team B fails. It overwrites Teams A's score and the element for Team B's score disappears completely?

teamResults[1].splice(1,2,4); 

["A" ,4 ,"B"]

Any advice on how to produce the following array would be greatly appreciated

["A" ,3 ,4 ,"B"]

Upvotes: 1

Views: 61

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386604

Why not assign the value with the index, without splicing.

teamResults[1][1] = 3;

Upvotes: 2

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

The Array.prototype.splice() syntax is:

var arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

So teamResults[1].splice(1,2,4); will remove 2 element from index 1 and then add 4.

In your case it should be teamResults[1].splice(2,1,4);

var arr = ["A" ,3 ,undefined ,"B"];

arr.splice(2, 1, 4);

console.log(arr)

Upvotes: 2

Related Questions