0

I'm cycling through this array and I want each array object to get a random color, but it keeps adding i behind the getRandomColor() instead of adding to the variable.

So it ends up like e.g #0A60860 + i

Why is that?

My app.js

function getRandomColor() {
  return "#" + Math.random().toString(16).slice(2,8);
}
let randomcolor = getRandomColor()
let randomcolor0 = getRandomColor()
let randomcolor1 = getRandomColor()
let randomcolor2 = getRandomColor()
let randomcolor3 = getRandomColor()
let randomcolor4 = getRandomColor()
let randomcolor5 = getRandomColor()
let randomcolor6 = getRandomColor()
let randomcolor7 = getRandomColor()
let randomcolor8 = getRandomColor()
let randomcolor9 = getRandomColor()
let randomcolor10 = getRandomColor()

var items = [{id: 24550986,username: "addwell",matchmaking_group_id: 5378563},{id: 30168682,username: "ekkelito",matchmaking_group_id: 5378563},{id: 41526903,username: "dkMrGOD",matchmaking_group_id: 5373230},{id: 87892435,username: "FluffyBunny",matchmaking_group_id: 5373230},{id: 115472481,username: "hinter",matchmaking_group_id: 5378563},{id: 290200108,username: "Jonatan",matchmaking_group_id: 5376993},{id: 296745880,username: "Joy",matchmaking_group_id: 5376993},{id: 352928851,username: "DiktatorN",matchmaking_group_id: 5376993},{id: 932540677,username: "MIKEEEEEEY",matchmaking_group_id: 5378560},{id: 1030322875,username: "fknbr0r",matchmaking_group_id: 5377517}],
  keys = { matchmaking_group_id: 'sections', username: 'items' }, // or more if required
  result = [],
  temp = { _: result };

items.forEach(function (object) {
  Object.keys(keys).reduce(function (level, key) {
    if (!level[object[key]]) {
      level[object[key]] = { _: [] };
      level._.push({ [key]: object[key], [keys[key]]: level[object[key]]._ });
    }
    return level[object[key]];
  }, temp)._.push({ title: object.title, description: object.description });
});

var arrayLength = result.length;
for (var i = 0; i < arrayLength; i++) {
  console.log(result[i]);
  console.log(i)
  randomcolor = randomcolor + i;

  var arrayLengthsections = result[i].sections.length;
  for (var ii = 0; ii < arrayLengthsections; ii++) {
    console.log(result[i].sections[ii].username)
    $( `span:contains('${result[i].sections[ii].username}')` ).css("border", '1px solid ' + randomcolor)
    console.log(randomcolor)
  }
}

  • 2
    What is `randomcolor = randomcolor + i;` supposed to do? – Robo Robok Apr 25 '20 at 02:23
  • 1
    `randomcolor + i` will be treated as a string concatenation because `randomcolor` is a string. So, in this case, it is the expected output. Not sure what you wanted to do there but there must be another way for achieving it – Cornel Raiu Apr 25 '20 at 02:43
  • This is off topic, but I when I saw this `Object.keys().reduce()` and it took me an insane amount of thinking to figure out what was going on. This is because it is being used for the wrong thing, I recommend watching this https://www.youtube.com/watch?v=qaGjS7-qWzg – Vitim.us Apr 25 '20 at 03:06

2 Answers2

1

I see multiple things that are not ideal with this piece of code, but I'll assume that you're a beginner.

First thing, this is not an Array, they are just multiple variables.

let randomcolor = getRandomColor()
let randomcolor0 = getRandomColor()
let randomcolor1 = getRandomColor()
let randomcolor2 = getRandomColor()
let randomcolor3 = getRandomColor()
let randomcolor4 = getRandomColor()
let randomcolor5 = getRandomColor()
let randomcolor6 = getRandomColor()
let randomcolor7 = getRandomColor()
let randomcolor8 = getRandomColor()
let randomcolor9 = getRandomColor()

but it keeps adding i behind the getRandomColor() instead of adding to the variable.

You cannot access a variable by "making its name" like this:

randomcolor = randomcolor + i;

You should create an array instead, there are many ways you can create arrays in javascript (creating an empty one and add values after, create a already populated, etc)

const randomColors = [
    getRandomColor(),
    getRandomColor(),
    getRandomColor(),
    getRandomColor(),
];

This will create an array with 4 values in it. This syntax is called "Literal array" see this answer about arrays

Then you access it using randomColors[i]

But from what I can see you don't even need to create those colors in advance and store then, you could just:

for (let ii = 0; ii < arrayLengthsections; ii++) {
    $( `span:contains('${result[i].sections[ii].username}')` )
        .css("border", '1px solid ' + getRandomColor())
}
Vitim.us
  • 16,145
  • 12
  • 81
  • 96
0

Consider the following example.

$(function() {
  function getRandomColor() {
    return "#" + Math.random().toString(16).slice(2, 8);
  }

  function drawContent(data) {
    $.each(data, function(i, el) {
      $("<span>").html(el.username).appendTo($(".content"));
    });
  }

  var items = [{
    id: 24550986,
    username: "addwell",
    matchmaking_group_id: 5378563
  }, {
    id: 30168682,
    username: "ekkelito",
    matchmaking_group_id: 5378563
  }, {
    id: 41526903,
    username: "dkMrGOD",
    matchmaking_group_id: 5373230
  }, {
    id: 87892435,
    username: "FluffyBunny",
    matchmaking_group_id: 5373230
  }, {
    id: 115472481,
    username: "hinter",
    matchmaking_group_id: 5378563
  }, {
    id: 290200108,
    username: "Jonatan",
    matchmaking_group_id: 5376993
  }, {
    id: 296745880,
    username: "Joy",
    matchmaking_group_id: 5376993
  }, {
    id: 352928851,
    username: "DiktatorN",
    matchmaking_group_id: 5376993
  }, {
    id: 932540677,
    username: "MIKEEEEEEY",
    matchmaking_group_id: 5378560
  }, {
    id: 1030322875,
    username: "fknbr0r",
    matchmaking_group_id: 5377517
  }];
  
  console.log("items", items);

  drawContent(items);

  $.each(items, function(i, obj) {
    console.log("-Needle: " + obj.username);
    $(".content > span").each(function(j, el) {
      console.log("--Stack: " + $(el).text());
      if ($(el).text().indexOf(obj.username) == 0) {
        $(el).css("border", '1px solid ' + getRandomColor());
        console.log("---Hit^: " + $(el).attr("style"));
      }
    });
  });
});
.content span {
  display: inline-block;
  padding: 2px;
  margin-right: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content"></div>

If you return a String, and concatenate an Integer, it will not add it but will append to the String. e.g. where i is 1, #0A60860 + i would be #0A608601 and not #0A60861. This is also too many characters for a proper color code. #0A6086, #000000, and #FFFFFF would be correct.

Twisty
  • 23,484
  • 1
  • 22
  • 40