Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 给定具有特定顺序的1xn数组,如何对随机顺序的1xn数组进行排序以适合第一个数组?_Javascript_Arrays_Sorting - Fatal编程技术网

Javascript 给定具有特定顺序的1xn数组,如何对随机顺序的1xn数组进行排序以适合第一个数组?

Javascript 给定具有特定顺序的1xn数组,如何对随机顺序的1xn数组进行排序以适合第一个数组?,javascript,arrays,sorting,Javascript,Arrays,Sorting,我有一个1xn大小的数组,其中顺序和索引位置很重要。可能很大 recipe = ['flour', 'eggs', 'apples', 'cinnamon', 'baking powder', 'sugar'] 假设我有一个函数,它返回两个随机排列的数组 另一个配方值=[2,4,6] 其中,值对应于单独1xn数组中的以下键 另一个食谱\u键=[‘苹果’、‘糖’、‘蛋’] 对两个数组进行排序以适应/匹配第一个数组中的n维是一种优雅的方式还是一种快速的方式 像这样 new_recipe_value

我有一个1xn大小的数组,其中顺序和索引位置很重要。可能很大

recipe = ['flour', 'eggs', 'apples', 'cinnamon', 'baking powder', 'sugar']
假设我有一个函数,它返回两个随机排列的数组

另一个配方值=[2,4,6]

其中,值对应于单独1xn数组中的以下键

另一个食谱\u键=[‘苹果’、‘糖’、‘蛋’]

对两个数组进行排序以适应/匹配第一个数组中的n维是一种优雅的方式还是一种快速的方式

像这样

new_recipe_values = [ 0, 6, 2, 0, 0, 4] 
new_recipe_keys = [ null, 'eggs', 'apples', null, null, 'sugar']
*更新编辑的输出变量。

我会选择

const recipe = ['flour', 'eggs', 'apples', 'cinnamon', 'baking powder', 'sugar']

let another_recipe_values = [ 2, 4, 6 ];
let another_recipe_keys = [ 'apples', 'sugar', 'eggs']

const indices = recipe.map(ingredient => another_recipe_keys.indexOf(ingredient));

another_recipe_values = indices.map(i => i<0 ? 0 : another_recipe_values[i]);
another_recipe_keys = indices.map(i => i<0 ? null : another_recipe_keys[i]);
您还可以从两个数组中动态构建另一个配方对象。

只需使用
map()
函数并将
0
值的位置设置为null

recipe.map((值,索引)=>recipe\u值[索引]!=0?值:null)

var配方=['面粉'、'鸡蛋'、'苹果'、'肉桂'、'发酵粉'、'糖']
变量配方_值=[0,6,2,0,0,4]
var result=recipe.map((值,索引)=>recipe\u值[索引]!=0?值:null)

console.log(result)
只需返回
null
即可,其中
另一个配方值中的值为
0
,否则使用该值作为配方的索引

var配方=[“面粉”、“鸡蛋”、“苹果”、“肉桂”、“发酵粉”、“糖”];
var另一个公式值=[0,6,2,0,0,4];
var输出=另一个配方\u值.map((s,i)=>s?配方[i]:null);

控制台日志(输出)什么是排序?使用映射函数我更喜欢
recipe
作为配料->索引的哈希映射。是的,这是正确的。@gurvinder372 0-basedindex@gurvinder372对了,OP对输入和结果使用了相同的变量名。固定的。
const ordered_ingredients = ['flour', 'eggs', 'apples', 'cinnamon', 'baking powder', 'sugar']
const another_recipe = {
    apples: 2,
    sugar: 4,
    eggs: 6
};
const another_recipe_values = ordered_ingredients.map(ing =>
    ing in another_recipe ? another_recipe[ing] : 0
);
const another_recipe_keys = ordered_ingredients.map(ing =>
    ing in another_recipe ? ing : null
);