LSB
LSB

Reputation: 3

Finding Value in an Indexed array

I have created a function that checks a nested array to see whether an input is valid. For the input to be valid it cannot have the same name twice in the array. Arr[i][0] contains the name of the crop.

 function checkList(arr,cropName) {
    for (i = 0; i < 32; i++) {
        if (arr[i][0] == cropName){
            console.log("Name in Array")
            return true;
        } else {
            console.log("Name not in Array")
            return false;
        }

    }  
}

for some reason this algorithm doesn't work, but i'm sure it should, any help is appreciated. I have set up a JS fiddle so you can look at it if needed.

https://jsfiddle.net/qdzvr6z1/

Upvotes: 0

Views: 59

Answers (2)

RobM
RobM

Reputation: 3609

=== UPDATED ANSWER ===
If this is useful, please vote up my answer. :)

To share some ideas on how you can clean up some code (there would be more to do, but I need to stop to get back to my work), I refactored and enhanced your solution.

Give it a try here Fiddle

html:

<canvas id="myCanvas" width="400" height="200" style="border:1px solid #000000;"></canvas><br>
<input type="color" id="currentColour" value="#ff0000">
<input type="text" id="cropName" placeholder="Please enter a color name"><br>
Mode:<br>
<div style="margin-left: 20px;">
    <input type="radio" id="modeAdd" name="mode" value="add" checked>Add</input><br>
    <input type="radio" id="modeClear" name="mode" value="clear">Clear</input>
</div>
<div>
    <p>Hover over a cell to see the values here:</p>
    <div style="margin-left: 20px;">
        Name: <input type="text" id="hoverName" /><br>
        Colour: <input type="text" id="hoverColour" />
    </div>
</div>

script:

    const defaultColour = "#ffffff";
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var numColours = 32;
    var colours = initialiseArray(numColours, defaultColour);

    function initialiseArray(qty, defaultColour) {
        var arr = [];
        for (i = 0; i < qty; i++) {
            arr.push({
                name: "",
                colour: defaultColour
            });
        };
        return arr
    };

    //DRAW GRID
    function drawGrid() {

        var step;
        ctx.setTransform(1, 0, 0, 1, 0.5, 0.5);
        ctx.beginPath();

        //Draw Vertical Lines
        for (step = 50; step < 400; step += 50) {
            ctx.moveTo(step, 0);
            ctx.lineTo(step, 200);
        }
        //Draw Horizontal Lines
        for (step = 50; step < 200; step += 50) {
            ctx.moveTo(0, step);
            ctx.lineTo(400, step);

            //Draw Dividers
            ctx.moveTo(200.5, 0);
            ctx.lineTo(200.5, 200);

            ctx.moveTo(0, 100.5);
            ctx.lineTo(400, 100.5);
        }

        ctx.stroke();
        ctx.setTransform(1, 0, 0, 1, 0, 0);
    }


    //GET MOUSE COORDINATES ON CANVAS
    function getMousePos(canvas, evt) {
        var rect = c.getBoundingClientRect();
        return {
            x: evt.clientX - rect.left,
            y: evt.clientY - rect.top
        };
    }

    function isColourNameProvided(name) {
        if (name) return true
        else return false;
    }

    // looks through an array of colour objects and returns true if the same name AND colour value combo exists
    function isDuplicateNameAndColourValue(newColourName, newColourValue) {
        return colours.some( c => c.name === newColourName && c.colour === newColourValue);
    }

    function isUserInputValid(arr, cropName, cropColour) {
        if (!isColourNameProvided(cropName)) {
            alert("Please set a name for the colour.");
            return false;
        }

        // Check to see if the combination of name and colour value already exists in the palette
        if (isDuplicateNameAndColourValue(cropName, cropColour)) {
            alert("That combination of NAME and COLOUR VALUE already exists in the palette.");
            return false;
        }

        return true;
    }

    function getMode() {
        var radios = document.getElementsByName("mode");
        for (i = 0; i < radios.length; i++) {
            if (radios[i].checked) return radios[i].value;
        }
        return null;
    }

    function updatePalette(event) {
        var cropName;
        var cropColour;
        var mousePos = getMousePos(c, event);
        var xPos = Math.floor(mousePos.x / 50) * 50 + 1;
        var yPos = Math.floor(mousePos.y / 50) * 50 + 1;
        var width = 49;
        var height = 49;
        var cellNum = Math.floor(mousePos.y / 50) * 8 + Math.floor(mousePos.x / 50)

        switch (getMode().toUpperCase()) {
            case "ADD":
                cropName = document.getElementById("cropName").value;
                cropColour = document.getElementById("currentColour").value;
                if (isUserInputValid(colours, cropName, cropColour)) {
                    updatePaletteCell(cellNum, cropName, cropColour, xPos, yPos, width, height);
                }
                break;
            case "CLEAR":
                cropName = "";
                cropColour = defaultColour;
                updatePaletteCell(cellNum, cropName, cropColour, xPos, yPos, width, height);
                break;
            default:
                alert("Unable to determine the mode.");
                break;
        }
    }

    function updatePaletteCell(cellNum, colourName, colourValue, xPos, yPos, width, height) {
        // paint the cell
        ctx.fillStyle = colourValue;
        ctx.fillRect(xPos, yPos, width, height);

        // store values for the cell
        colours[cellNum].name = colourName;
        colours[cellNum].colour = colourValue;
    }


    function showColourInfo(event) {
        var mousePos = getMousePos(c, event);
        var cellNum = Math.floor(mousePos.y / 50) * 8 + Math.floor(mousePos.x / 50)
        crop = colours[cellNum];
        if (crop) {
            document.getElementById("hoverName").value = crop.name;
            document.getElementById("hoverColour").value = crop.colour;
        }
    }

    c.addEventListener('mousemove', showColourInfo, false);
    c.addEventListener('click', updatePalette, false);

    drawGrid();

=== ORIGINAL ANSWER ===
The answer Daniel gave is correct, but I think it's better refactored to be like this:

function checkList(arr,cropName) {
    var result = arr.some(x => {
        return (x[0] === cropName);
    });
    console.log("Duplicate found = ", result);
    return result;
}

Note: This (and the one you posted) will return true in your fiddle right now because you aren't checking before you update the cell, so it will always be found.

Another quick tip: if (checkInput != false) is commonly done like this: if (checkInput), as this returns true for all values except: false, 0, "", null, undefined, and NaN

Upvotes: 0

Daniel
Daniel

Reputation: 6491

You're returning on the first iteration so you're only checking index 0.

Try

function checkList(arr,cropName) {
    for (i = 0; i < 32; i++) {
        if (arr[i][0] == cropName){
            console.log("Name in Array")
            return true;
        }
    }
    console.log("Name not in Array")
    return false;
}

Upvotes: 2

Related Questions