[英]i have flat state of arrays in react and i want to make it nested array and push it to another object ins state
[英]i want to push arrays into array
我有兩個參數和兩個 arguments,其中一個應該是數字,另一個應該是數組,如果數組中的數字是相似的項目,我應該提取相似的數字然后再次將它們推入數組,並保持順序不相似的數字,我已經寫了這段代碼,但它不起作用,我花了兩天多的時間試圖弄清楚這一點,但還沒有結果。
function extractNumber(num, nums) {
if(nums.includes(num)===true){
for (let i = 0; i <nums.length; i++) {
if(nums[i]=== num){
var popped = nums.splice(i,1);
i--;
nums.push(popped);
}
}
}
return nums;
}
extractNumber(7, [1,2,7,1,7,1,7,3,7,1]);
像這樣的東西?
你的標題有點誤導。
function extractNumber(num, nums) { nums.forEach((i, index) => { //loop each item in nums if (i === num) { //if current item is same as num nums.splice(index, 1) //remove it from its position.. nums.push(i) //..and push it at the end of the array } }) return nums } console.log(extractNumber(7, [1, 2, 7, 1, 7, 1, 7, 3, 7, 1]))
我認為您的代碼只有幾個問題:
Array#push
popped
一個數組,而是推送num
。i--
我——因為那不是必需的。 我喜歡您的方法,因為如果num
不是數組的元素,您可以避免不必要的循環。 因此,您更正后的代碼如下所示:
function extractNumber(num, nums) { if( nums.includes(num) ) { for (let i = 0; i <nums.length; i++) { if(nums[i] === num){ nums.splice(i,1); nums.push(num); } } } return nums; } console.log( extractNumber(7, [1,2,7,1,7,1,7,3,7,1]) );
如果我明白你想要這樣的東西
function extractNumber(num, nums) {
const matrixFix = nums.reduce((acc, cv) => {
if (num !== cv) {
return { notSimilar: [...acc.notSimilar, cv], similar: [...acc.similar] }
};
return { notSimilar: [...acc.notSimilar], similar: [...acc.similar, cv]
};
}, { similar: [], notSimilar: [] })
return [...matrixFix.notSimilar, ...matrixFix.similar];
}
extractNumber(7, [1, 2, 7, 1, 7, 1, 7, 3, 7, 1]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.