Using an array to filter an array Javascript

北城余情 提交于 2019-12-25 12:45:11

问题


I am trying to look at every value in one array and see if any of them are contained in any of the other array values. Ex:

arrOne = ['a', 'b' ,'c' ];
arrTwo = ['option a', 'option c', 'option b', 'option d'];

So I want it to cycle through to see every value in arrTwo that has one of the values from arrOne and remove the ones that dont so I get:

arrFinal = ['option a', 'option c', 'option b'];

Here is the code I am working with:

JavaScript

function PreSaveAction() {
var Fields = ['input','select','textarea']
var ReqEmpty = 0;
var RowNum = ( $('table.input-table > tbody > tr').length);
var type = [];
var typeFinal = [];
var FieldType;
var FieldTypeNum;

for(var i=0; i<=(RowNum - 1); i++){
    type.push( $("table.input-table > tbody > tr").eq(i).html());
};
alert(type.length); 



//Where a need the filter code
//using Req as arrOne and type as arrTwo




for(var i = 0; i <= (type.length - 1); i++){

    for(var ii = 0; ii <= (Fields.length - 1); ii++){
        if(type[i].indexOf(Fields[ii]) == -1){
            FieldType = (Fields[ii]);
            break;
        };
    };

    for(var i=0; i <= (Req.length - 1); i++){
        if($('.more-options').is(':visible') && ($("" + FieldType + "[title=" +"'" + Req[i] + "'"+ "]").val() == "") )
        {
            ReqEmpty += 1;          
        };
    };
};



if(ReqEmpty == 0)
{
    return true;

}else if(ReqEmpty == 1){
    alert("There is 1 empty required field");
    return false;
}else{  
    alert("There are " + ReqEmpty + " empty required fields");
    return false;
};
};

HTML Generated with SharePoint

<table border="0" cellspacing="0" width="100%" class="input-table">
                <tr>
                    <td width="190px" valign="top" class="ms-formlabel">
                        <H3 class="ms-standardheader">
                            <nobr>Title<span class="ms-formvalidation"> *</span>
                            </nobr>
                        </H3>
                    </td>
                    <td width="400px" valign="top" class="ms-formbody">
                        <SharePoint:FormField runat="server" id="ff1{$Pos}" ControlMode="Edit" FieldName="Title" __designer:bind="{ddwrt:DataBind('u',concat('ff1',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Title')}"/>
                        <SharePoint:FieldDescription runat="server" id="ff1description{$Pos}" FieldName="Title" ControlMode="Edit"/>
                    </td>
                </tr>
                <tr>
                    <td width="190px" valign="top" class="ms-formlabel">
                        <H3 class="ms-standardheader">
                            <nobr>Selector<span class="ms-formvalidation"> *</span>
                            </nobr>
                        </H3>
                    </td>
                    <td width="400px" valign="top" class="ms-formbody">
                        <SharePoint:FormField runat="server" id="ff5{$Pos}" ControlMode="Edit" FieldName="Selector" __designer:bind="{ddwrt:DataBind('u',concat('ff5',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Selector')}"/>
                        <SharePoint:FieldDescription runat="server" id="ff5description{$Pos}" FieldName="Selector" ControlMode="Edit"/>
                    </td>
                </tr>
                <tr>
                    <td width="190px" valign="top" class="ms-formlabel">
                        <H3 class="ms-standardheader">
                            <nobr>Required Hidden 1</nobr>
                        </H3>
                    </td>
                    <td width="400px" valign="top" class="ms-formbody">
                        <SharePoint:FormField runat="server" id="ff2{$Pos}" ControlMode="Edit" FieldName="Required_x0020_Hidden_x0020_1" __designer:bind="{ddwrt:DataBind('u',concat('ff2',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Required_x0020_Hidden_x0020_1')}"/>
                        <SharePoint:FieldDescription runat="server" id="ff2description{$Pos}" FieldName="Required_x0020_Hidden_x0020_1" ControlMode="Edit"/>
                    </td>
                </tr>
                <tr>
                    <td width="190px" valign="top" class="ms-formlabel">
                        <H3 class="ms-standardheader">
                            <nobr>Required Hidden 2</nobr>
                        </H3>
                    </td>
                    <td width="400px" valign="top" class="ms-formbody">
                        <SharePoint:FormField runat="server" id="ff3{$Pos}" ControlMode="Edit" FieldName="Required_x0020_Hidden_x0020_2" __designer:bind="{ddwrt:DataBind('u',concat('ff3',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Required_x0020_Hidden_x0020_2')}"/>
                        <SharePoint:FieldDescription runat="server" id="ff3description{$Pos}" FieldName="Required_x0020_Hidden_x0020_2" ControlMode="Edit"/>
                    </td>
                </tr>
                <tr>
                    <td width="190px" valign="top" class="ms-formlabel">
                        <H3 class="ms-standardheader">
                            <nobr>Not Required Hidden 1</nobr>
                        </H3>
                    </td>
                    <td width="400px" valign="top" class="ms-formbody">
                        <SharePoint:FormField runat="server" id="ff4{$Pos}" ControlMode="Edit" FieldName="Not_x0020_Required_x0020_Hidden_" __designer:bind="{ddwrt:DataBind('u',concat('ff4',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Not_x0020_Required_x0020_Hidden_')}"/>
                        <SharePoint:FieldDescription runat="server" id="ff4description{$Pos}" FieldName="Not_x0020_Required_x0020_Hidden_" ControlMode="Edit"/>
                    </td>
                </tr>
                <tr>
                    <td width="190px" valign="top" class="ms-formlabel">
                        <H3 class="ms-standardheader">
                            <nobr>Did It Work</nobr>
                        </H3>
                    </td>
                    <td width="400px" valign="top" class="ms-formbody">
                        <SharePoint:FormField runat="server" id="ff6{$Pos}" ControlMode="Edit" FieldName="Did_x0020_It_x0020_Work" __designer:bind="{ddwrt:DataBind('u',concat('ff6',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Did_x0020_It_x0020_Work')}"/>
                        <SharePoint:FieldDescription runat="server" id="ff6description{$Pos}" FieldName="Did_x0020_It_x0020_Work" ControlMode="Edit"/>
                    </td>
                </tr>

                <tr id="idAttachmentsRow"><td nowrap="true" valign="top" class="ms-formlabel" width="20%"><SharePoint:FieldLabel ControlMode="Edit" FieldName="Attachments" runat="server" /></td><td valign="top" class="ms-formbody" width="80%"><SharePoint:FormField runat="server" id="AttachmentsField" ControlMode="Edit" FieldName="Attachments" __designer:bind="{ddwrt:DataBind('u','AttachmentsField','Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Attachments')}" /><script>
      var elm = document.getElementById(&quot;idAttachmentsTable&quot;);
      if (elm == null || elm.rows.length == 0)
      document.getElementById(&quot;idAttachmentsRow&quot;).style.display=&apos;none&apos;;
    </script></td></tr>
                <xsl:if test="$dvt_1_automode = '1'" ddwrt:cf_ignore="1">
                    <tr>
                        <td colspan="99" class="ms-vb">
                            <span ddwrt:amkeyfield="ID" ddwrt:amkeyvalue="ddwrt:EscapeDelims(string(@ID))" ddwrt:ammode="view"></span>
                        </td>
                    </tr>
                </xsl:if>
            </table>

Any help would be appreciated


回答1:


This is probably not the best way of doing this, but it does work. It uses type for arrTwo and Req for ArrOne.

for(var i = (type.length - 1); i >= 0 ; i--){
    var SpliceVal = 0;

    for(var ii = 0; ii <= (Req.length -1); ii++){
        if(type[i].indexOf(Req[ii]) == -1){
            SpliceVal += 1;    
        };  
    };

    if(SpliceVal == Req.length){
        type.splice(i, 1);
    };
};



回答2:


There are two possible ways to address this, depending on how you lay out your arrays.

Option one -- assumes both arrays will have matching value structures

var arrOne = ['option a', 'option b', 'option c'];
var arrTwo = ['option a', 'option c', 'option b', 'option d'];
var arrFinal = [];

$(document).ready(function () {
    $.each(arrOne, function (key, value) {
        var index = $.inArray(value, arrTwo);
        if (index != -1) {
            arrFinal.push(arrTwo[index]);
            console.log(value);
        }
   });
});

Option two -- assumes both arrays will not have matching value structures (your example above)

 var arrOne = ['a', 'b', 'c'];
 var arrTwo = ['option a', 'option c', 'option b', 'option d'];
 var arrFinal = [];

 $(document).ready(function () {
     $.each(arrOne, function (key1, value1) {
         $.each(arrTwo, function (key2, value2) {
            var index = value2.indexOf(value1);
            if (index != -1) {
                arrFinal.push(value2);
                console.log(value2);
            }
         });
     });
 });



回答3:


Just loop through and add the ones it finds to a new array. No need for splicing.

function result(arr1, arr2) {
    var out = [];
    for (var i = 0, l = arr2.length; i < l; i++) {
        var el2 = arr2[i];
        var rel2 = el2.replace('option ', '');
        if (arr1.indexOf(rel2) > -1) { out.push(el2); }
    }
    return out;
}

result(arr1, arr2);

DEMO




回答4:


If you can use an third party library, you can use underscorejs, which provides lots of utility functions.

function customFilter(arrOne, arrTwo) {
    return _.filter(arrTwo, function(item){
       var res = item.substring('option '.length, item.length);   
       return _.contains(arrOne, res);
    });
}

var result = customFilter(arrOne, arrTwo);

DEMO




回答5:


JavaScript

Array.prototype.Filter = function(filters)
{
    var t = new Array();
    for(var i = 0; i < this.length; ++i)
    {
        for(var j = 0; j < filters.length; ++j)
        {
            if(this[i].contains(filters[j]))
            {
                t.push(this[i]);
            }
        }
    }
    return(t);
};

/* Exemple */
var filters = [ 'a', 'b' ,'c' ];
var arr = [ 'option a', 'option c', 'option b', 'option d' ];
var result = arr.Filter(filters);
alert(result);


来源:https://stackoverflow.com/questions/25529018/using-an-array-to-filter-an-array-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!