How to check if a new row of inputs is redundant with previous rows (array)

Viewed 96

I have a form which consists of an array of input fields.

Is there any way I could verify the inputs in every row and check if they have at least one unique value in any one field so that there will be none identical rows?

For example, 2nd row is allowed to only have 3 out of 4 fields with exact values similar to those in 1st row, at max.

<form>
     <div>
        <table>
            <tr v-for="(item, i) of items" :key="i">
                <td>
                    <input type="date" :id="'date-' + i">
                </td>
                <td>
                    <input type="text" :id="'project_id-' + i">
                </td>
                <td>
                    <input type="text" :id="'hours-' + i">
                </td>
                <td>
                    <input type="text" :id="'description-' + i">
                </td>
            </tr>
            <tr>
                <td>
                    <button type="button" @click="itemCount++">Add Row</button>
                </td>
            </tr>
        </table>
    </div>
    <div>
        <button type="button" v-on:click="submit()">
    </div>
</form>

I have came across a technique using distinctvalidation but uncertain of its practicality besides of the correct syntax and flow.

1 Answers

In the submit() function, convert the items array to a Set in order to remove the redundant values. Next, re-convert to Array again to be able to compare the two arrays by their length. If the lengths are different, then it means there is(are) redundant value(s) existed.

submit() {
    const arr = this.items        
    var obj = arr.map(JSON.stringify)      
    var set = new Set(obj)
    var unique = Array.from(set).map(JSON.parse)              
    console.log(obj, set, unique);

    if(obj.length != unique.length) {
        alert("Error: Redundant inputs!")
    } else {
        // submit the form
    };
}

STEPS:

  • First, convert each object of the arr array into a JSON encoded string using JSON.stringify method.

  • Secondly, map the JSON encoded string to a new array obj using the map() method.

  • Thirdly, create a new set by passing the obj array to the new set constructor to remove all the duplicate elements.

    This set will only holds the values that are unique from the array.

  • Then, convert the set to another array unique using the from() method by passing the set as a parameter.

    This new array will not have any redundant objects from the previous array (if any).

  • Lastly, compare both arrays by their length to find out if they are equal or not. Unequal lengths indicate the presence of redundant input values.

Related