簡體   English   中英

如何獲取數組中兩個數字之間的值?

[英]How to get values between two numbers in an array?

["10","13"] 是數組,需要找到它們之間的值,並用值 -> ["10","11","12","13"] 展平數組。

上面的第一個數組 (["10", "13"]) 位於數組列表中。

const OriginalData = {
   Red:{
      Name:"L",
      List:[
         ["1", "5"],
         ["2", "5"],
         ["7", "9" ],
      ]
   },
   Blue:{
      Name:"BL",
      List:[
         ["1", "5"],
         ["7", "9" ],
         ["10", "13" ],
         ["15", "20"]
      ]
   },
   Black:{
      List:[
         ["Random"],
         "Random2"
      ]
   }
}

然后最后對象必須看起來像,

{
   Level:{
      Name:"L",
      List:[
        1, 2, 3, 4, 5, 7, 8, 9
      ]
   },
   Basement:{
      Name:"BL",
      List:[
        1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20
     ] 
   },
   Custom:{
      List:[
         "Random",
         "Random2"
      ]
   }
}

它應該做什么:取第一個對象,在 List 里面有一組范圍,這些范圍之間的值應該找到一個沒有重復的展平。 查找之間的值僅適用於“紅色”和“藍色”,在“黑色”鍵中只需要展平。

我試過了,

代碼:

  const submitData = () => {
    let obj = originalData;
    let flattenedArray = [].concat.apply([], originalData.Red.List);
    let uniqueArray = flattenedArray.filter(
      (v, i, a) => a.indexOf(v) === i
    );
    obj = {
      ...originalData,
      Red: {
        ...originalData.Red,
        List: uniqueArray,
      },
    };
    console.log(obj);
  };

上面的代碼使數組變平,但在數字之間找不到,它只適用於鍵“紅色”

創建范圍的簡單示例:

 let example = ["10","13"]; let min = Math.min(...example); let max = Math.max(...example); let result = []; for (i = min; i <= max; i++) { result.push(i); } console.log(min, max, result)

您可以通過簡單的邏輯輕松實現它,並且也適用於隨機數。

試試這個(在下面的代碼片段中添加了實現的描述性注釋)

 const OriginalData = { Red:{ Name:"L", List:[ ["1", "5"], ["2", "5"], ["7", "9" ], ] }, Blue:{ Name:"BL", List:[ ["1", "5"], ["7", "9" ], ["10", "13" ], ["15", "20"] ] } }; Object.keys(OriginalData).forEach(key => { // Flatten the original array list. OriginalData[key].List = OriginalData[key].List.flat() // Find min and max numbers from the array. const min = Math.min(...OriginalData[key].List); const max = Math.max(...OriginalData[key].List); // empty existing list array. OriginalData[key].List = []; // Now using for loop assign the values to the list array based on min and max value. for (let i = min; i <= max; i++) { OriginalData[key].List.push(i); } }); // Result console.log(OriginalData);

要創建給定范圍內所有數字的數組,您可以創建一個具有所需大小的新數組,然后將每個條目映射到條目的索引加上給定的下限。

function fillRange(r) {
    let b = +r[1]
    let a = +r[0]
    if (a > b) {
        let tmp = a
        a = b
        b = tmp
    }
    return Array(b - a + 1).fill(0).map((e, i) => a + i)
}

此函數展平數組並刪除所有重復條目。

function union(arrays) {
    let flattened = [].concat.apply([], arrays)
    return flattened.reduce(
            (total, e) => {
                let i = total.indexOf(e)
                if (i === -1) {
                    total.push(e)
                }
                return total
            }, [])
}

然后此代碼從范圍列表中生成所需的結果:

function unionRanges(ranges) {
    let expanded = ranges.map((e) => fillRange(e))
    return union(expanded).sort((a,b) => (a-b))
}

最終對象可以這樣創建:

function processData(data) {
    let res = {}
    res.Level = {}
    res.Basement = {}
    res.Custom = {}
    
    res.Level.Name = data.Red.Name;
    res.Level.List = unionRanges(data.Red.List)
    
    res.Basement.Name = data.Blue.Name
    res.Basement.List = unionRanges(data.Blue.List)
    
    res.Custom.List = union(data.Black.List)
    
    return res
}

您可以展平數組,獲取最小值和最大值,最后使用循環創建所需的數組。

 const array = [["1","5"],["7","9"],["10","13"],["15","20"]]; const flatted = array.flat(); const min = Math.min(...flatted); const max = Math.max(...flatted); const result = Array.from({length: max + 1 - min}).map(function(_, i) { return i + min; }); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

希望以下代碼對您有所幫助。

const OriginalData = {
    Red: {
        Name: "L",
        List: [
            ["1", "5"],
            ["2", "5"],
            ["7", "9"],
        ]
    },
    Blue: {
        Name: "BL",
        List: [
            ["1", "5"],
            ["7", "9"],
            ["10", "13"],
            ["15", "20"]
        ]
    },
    Black: {
        List: [
            ["Random"],
            "Random2"
        ]
    }
};

//Iterating over the object OriginalData
Object.keys(OriginalData).forEach(key => {
    // Flatten the array "List" of each element
    OriginalData[key].List = OriginalData[key].List.flat();

    // Checking if the flatten array contains integers
    if (!isNaN(parseInt(OriginalData[key].List[0]))) {
        // Calculating the min and max of the "List" array
        const min = Math.min(...OriginalData[key].List);
        const max = Math.max(...OriginalData[key].List);

        let tmpArr = [];
        // Generating the array with numbers from min to max
        for (let i = min; i <= max; i++) {
            tmpArr.push(i);
        }
        // Updating the original "List" (containing integers) of each element
        OriginalData[key].List = tmpArr;
    }
});

console.log(OriginalData);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM