gpt4 book ai didi

javascript - 如果满足条件,Lodash 交换相邻的项目

转载 作者:行者123 更新时间:2023-11-30 17:00:12 25 4
gpt4 key购买 nike

假设我有一个数组,[1, 2, 3, 4, 5, 3, 4, 6, 3, 7, 4]。我想交换 3 和 4 的值,前提是它们按 [3, 4] 的顺序相邻(即 [4, 3] 保持不变)。该示例的结果将是 [1, 2, 4, 3, 5, 4, 3, 6, 3, 7, 4]

在不使用 for 循环的情况下,在 Lodash 中是否有一种优雅的方式来做到这一点?

编辑:怎么样

 _.sortBy(arr, function(value, index) {
if (value === 3) {
return index + 0.75;
} else if (value === 4) {
return index - 0.75;
} else {
return index
}
});

编辑 2:进行以下操作(实际上不是 3 和 4)。

return _.reduce(tags, function(out, tag) {
var word = tag[0];

if (out[0] && unitPowerSuffixes.hasOwnProperty(word)) {
out.splice(-1, 0, {
type: 'unit-power',
value: unitPowerSuffixes[word]
}); // Insert one from end
} else {
out.push(tag);
}

return out;
}, []);

最佳答案

Is there an elegant way to do this in Lodash without the use of for loops?

是的,您可以按如下方式使用reduce:

var array  = [1, 2, 3, 4, 5, 3, 4, 6, 3, 7, 4];

var result = _.reduce(array, swapAdjacentInOrder(3, 4), []);

alert(JSON.stringify(result));

function swapAdjacentInOrder(a, b) {
return function (result, element) {
var length = result.length;

if (length > 0 && element === b) {
var last = length - 1;

if (result[last] === a) {
result[last] = b;
element = a;
}
}

result[length] = element;

return result;
};
}
<script src="https://rawgit.com/lodash/lodash/master/lodash.min.js"></script>

但是,swapAdjacentInOrder 函数还具有以下属性:

var array  = [3, 4, 4, 4];

var result = _.reduce(array, swapAdjacentInOrder(3, 4), []);

alert(JSON.stringify(result)); // [4, 4, 4, 3]

function swapAdjacentInOrder(a, b) {
return function (result, element) {
var length = result.length;

if (length > 0 && element === b) {
var last = length - 1;

if (result[last] === a) {
result[last] = b;
element = a;
}
}

result[length] = element;

return result;
};
}
<script src="https://rawgit.com/lodash/lodash/master/lodash.min.js"></script>

如果您不希望这样做,则可以执行以下更新的 swapAdjacentInOrder 函数:

var array  = [3, 4, 4, 4];

var result = _.reduce(array, swapAdjacentInOrder(3, 4), []);

alert(JSON.stringify(result)); // [4, 3, 4, 4]

function swapAdjacentInOrder(a, b) {
return function (result, element) {
var length = result.length;

if (length > 0 && element === b) {
var last = length - 1;

if (result[last] !== a || last > 0 && result[last - 1] === b);
else {
result[last] = b;
element = a;
}
}

result[length] = element;

return result;
};
}
<script src="https://rawgit.com/lodash/lodash/master/lodash.min.js"></script>

希望对您有所帮助。

关于javascript - 如果满足条件,Lodash 交换相邻的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29030903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com