0

I am making a matchmaking system. My current function matched the players with a 20 difference in weight. As you can see on the result of my snippet, 1900 vs 1920 has been matched because i declared a different = 20,. Now my target is to make a dynamic different. I want to pass my textbox value to my different. I want to match player 2 and player 3. They do have 30 difference in weight.

If I type 30 on my textbox. Player 2 and Player 3 should be matched

. How can i achieve this? Any help will be appreciated. Thank you.

var difff = document.getElementById('diff'); // I have tried also to set a variable here to get the textbox value and pass it to my "different = difff" but it is not working.

const source = [
  {
    entryID: 1,
    entryName: "player1",
    weight: 1900,
  },
  {
    entryID: 2,
    entryName: "player2",
    weight: 1920,
  },  {
    entryID: 3,
    entryName: "player3",
    weight: 1950,
  },

];

function combine(
  data = [],
  different = 20, // I have tried to change the "20" to my id "difff" So i can pass my textbox's value but it is not working.
  maxGroupSize = 2,
  sortedStatement = (a, b) => a.weight - b.weight
) {
  const sortedData = [...data].sort(sortedStatement); // "weight" must be in ascending order

  const dataGroups = sortedData.reduce((acc, item) => {
    const findedAccItem = acc.find(
      (accItem) =>
        accItem.length < maxGroupSize && // if the array is not filled
        accItem[0].weight + different >= item.weight && // and if the minimum is in the acceptable range
        !accItem.find((obj) => obj.entryName === item.entryName /* || obj.entryID === item.entryID */) // and if there are no matches
    );
    if (findedAccItem) {
      findedAccItem.push(item);
    } else {
      acc.push([item]);
    }
    return acc;
  }, []);

  const namedDataGroups = dataGroups.reduce((acc, item, index) => {
    // added an index as a prefix because the keys can match
    const key = [index, ...item.map((item) => item.weight)].join("_");
    acc[key] = item;
    return acc;
  }, {});

  return namedDataGroups;
}

// default example
console.log("Example #1: ", combine(source));
<input id="diff" type="number" value="20"/> // I need to pass this on my script.
Dark
  • 132
  • 1
  • 15
  • `difff.value` will get you the value in the text box. – Barmar Feb 11 '22 at 04:14
  • Thank you for your reply, but it is not working. :( http://jsfiddle.net/rain0221/eaokyt8h/11/ – Dark Feb 11 '22 at 04:22
  • 1
    The value is a string, you need to convert it to a number if you're going to do arithmetic. Otherwise, the `+` operator is concatenation. – Barmar Feb 11 '22 at 04:24
  • 1
    `var difff = parseInt(document.getElementById('diff').value);` – Barmar Feb 11 '22 at 04:25
  • Perfect. Thank you so much. Can you post this as an answer so i can accept it? That was very dumb of me. It was so simple. x.x – Dark Feb 11 '22 at 04:36

0 Answers0