简体   繁体   中英

How to filter an array of objects based on the first character of a property in the array of object?

I am trying to filter through an array of objects based on the first number of a property and I can;t get it to work properly.

What I should have returning from the filter is the objects RowNumber has a starting row number of 1, and I need to use the filter method. I can probably use a for loop and get the objects that I am looking to have returned, but would rather use the filter method as its cleaner.

 (function() { const ds = [{ ID: 1, RowNumber: "1" }, { ID: 2, RowNumber: "1.01" }, { ID: 3, RowNumber: "1.02" }, { ID: 4, RowNumber: "1.03" }, { ID: 5, RowNumber: "2.01" } ]; const gridDs = [{ ID: 1, RowNumber: "1", Name: "Box 1" }, { ID: 2, RowNumber: "1.01", Name: "Box 2" }, { ID: 3, RowNumber: "1.02", Name: "Box 3" }, { ID: 4, RowNumber: "1.03", Name: "Box 4" }, { ID: 5, RowNumber: "", Name: "" }, { ID: 6, RowNumber: "2", Name: "" }, { ID: 7, RowNumber: "2.01", Name: "Box 7" }, { ID: 8, RowNumber: "2.02", Name: "Box 8" }, { ID: 9, RowNumber: "3", Name: "Box 9" }, ]; const firstItem = ds[0]; const itemSplit = firstItem.RowNumber.split("."); const foundItems = gridDs.filter(f => f.RowNumber === firstItem.RowNumber && f.RowNumber.split(".")[0] === parseInt(itemSplit)); console.log(foundItems); })();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

itemSplit is an array. You need to get the first element of it, and parse it to an integers.

In the filter() call, you shouldn't check f.RowNumber === firstItem.RowNumber since you only care about the part before . in f.rowNumber . Parse the first part of this, and compare it with the number you're searching for.

 (function() { const ds = [{ ID: 1, RowNumber: "1" }, { ID: 2, RowNumber: "1.01" }, { ID: 3, RowNumber: "1.02" }, { ID: 4, RowNumber: "1.03" }, { ID: 5, RowNumber: "2.01" } ]; const gridDs = [{ ID: 1, RowNumber: "1", Name: "Box 1" }, { ID: 2, RowNumber: "1.01", Name: "Box 2" }, { ID: 3, RowNumber: "1.02", Name: "Box 3" }, { ID: 4, RowNumber: "1.03", Name: "Box 4" }, { ID: 5, RowNumber: "", Name: "" }, { ID: 6, RowNumber: "2", Name: "" }, { ID: 7, RowNumber: "2.01", Name: "Box 7" }, { ID: 8, RowNumber: "2.02", Name: "Box 8" }, { ID: 9, RowNumber: "3", Name: "Box 9" }, ]; const firstItem = ds[0]; const searchNumber = parseInt(firstItem.RowNumber.split(".")[0]); const foundItems = gridDs.filter(f => parseInt(f.RowNumber.split(".")[0]) === searchNumber); console.log(foundItems); })();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM