Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/364.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 按字符串值对数组排序_Javascript_Arrays_Sorting - Fatal编程技术网

Javascript 按字符串值对数组排序

Javascript 按字符串值对数组排序,javascript,arrays,sorting,Javascript,Arrays,Sorting,如何按字符串值对数组排序 如果我有一个数组,比如['you'、'I'、'me'、'me'、'will'、'me'],我如何获得数组前面有单词me的所有索引 我尝试过使用array.sort,但它似乎不起作用 e、 target.value是我从可以使用sort的中获取的值 让a=['you'、'I'、'me'、'me'、'will'、'me']; a、 排序((a,b)=>a!==b&&b===me'?1:0); console.log(a)您可以使用sort 让a=['you'、'I'、'

如何按字符串值对数组排序

如果我有一个数组,比如
['you'、'I'、'me'、'me'、'will'、'me']
,我如何获得数组前面有单词
me
的所有索引

我尝试过使用array.sort,但它似乎不起作用

e、 target.value是我从可以使用sort的
中获取的值

让a=['you'、'I'、'me'、'me'、'will'、'me'];
a、 排序((a,b)=>a!==b&&b===me'?1:0);
console.log(a)
您可以使用sort

让a=['you'、'I'、'me'、'me'、'will'、'me'];
a、 排序((a,b)=>a!==b&&b===me'?1:0);
console.log(a)
使用
arr
上的
Array.prototype.sort()
方法,使用一个回调函数,该函数仅在第一个项与给定条件不匹配而第二个项与给定条件匹配时才切换项的顺序

arr.sort((item1, item2) => {
  if((item1.id !== 2 || item1.name !== 'foo') && (item2.id === 2 || item2.name === 'foo')) {
    return 1;
  }

  return 0;
});

console.log(arr);
使用
arr
上的
Array.prototype.sort()
方法,使用一个回调函数,该函数仅在第一个项与给定条件不匹配而第二个项与给定条件匹配时才切换项的顺序

arr.sort((item1, item2) => {
  if((item1.id !== 2 || item1.name !== 'foo') && (item2.id === 2 || item2.name === 'foo')) {
    return 1;
  }

  return 0;
});

console.log(arr);

你想找到单词“me”的所有索引吗?是的,然后将所有带有单词“me”的索引移动到数组的前面。所以索引0、1和2应该是我,然后索引3、4、5应该是‘你’、‘我’和‘威尔’,不是吗?
[‘我’、‘我’、‘我’、‘你’、‘威尔’]
如果你想对它们进行排序的话?其余的值都不重要,我只想让关键字‘我’出现在数组的前面。你想找到所有单词‘我’的索引吗,然后将所有带有单词“me”的索引移动到数组的前面。所以索引0、1和2应该是我,然后索引3、4、5应该是‘你’、‘我’和‘威尔’,不是吗
[‘我’、‘我’、‘我’、‘你’、‘威尔’]
如果你想对它们进行排序的话?其余的值都不重要,我只希望关键字‘我’位于数组的最前面非常好的方法(+1)如果你想在一个对象中有两个匹配的值呢?我已更新了我的问题以包含此问题。使用
b.propname
访问您要比较的属性我的每一个好方法(+1)。如果您希望在一个对象中有两个匹配的值,该怎么办?我已更新我的问题以包含此问题。请使用
b.propname
访问要比较的属性
const arr = [
  {id: 1, name: "cookie"},
  {id: 2, name: 'foo'},
  {id: 3, name: 'bar'},
  {id: 2, name: 'foo'}
];
arr.sort((item1, item2) => {
  if((item1.id !== 2 || item1.name !== 'foo') && (item2.id === 2 || item2.name === 'foo')) {
    return 1;
  }

  return 0;
});

console.log(arr);